Especialização em Backend com PHP & Laravel • Demonstrações Práticas Compiláveis


💻 Exemplo 1 — Comando Artisan Customizado

<?php
// app/Console/Commands/CleanTempCommand.php
namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;
use Carbon\Carbon;

class CleanTempCommand extends Command
{
    protected $signature = 'app:clean-temp {--days=7 : Dias de retenção dos arquivos}';
    protected $description = 'Remove arquivos temporários mais antigos que N dias';

    public function handle(): int
    {
        $dias = (int) $this->option('days');
        $limite = Carbon::now()->subDays($dias);
        $removidos = 0;

        foreach (File::files(storage_path('app/temp')) as $arquivo) {
            if (Carbon::createFromTimestamp($arquivo->getMTime())->lt($limite)) {
                File::delete($arquivo->getPathname());
                $removidos++;
            }
        }

        $this->info("Arquivos temporários removidos: {$removidos}");
        return Command::SUCCESS;
    }
}

💻 Exemplo 2 — Service Provider com Binding de Contrato

<?php
// app/Contracts/PaymentGatewayInterface.php
namespace App\Contracts;

interface PaymentGatewayInterface
{
    public function charge(int $centavos, string $token): bool;
}
<?php
// app/Services/StripePaymentGateway.php
namespace App\Services;

use App\Contracts\PaymentGatewayInterface;

class StripePaymentGateway implements PaymentGatewayInterface
{
    public function __construct(private readonly string $secretKey) {}

    public function charge(int $centavos, string $token): bool
    {
        // Chamada real à API do Stripe seria feita aqui.
        return $centavos > 0 && !empty($token);
    }
}
<?php
// app/Providers/PaymentServiceProvider.php
namespace App\Providers;

use App\Contracts\PaymentGatewayInterface;
use App\Services\StripePaymentGateway;
use Illuminate\Support\ServiceProvider;

class PaymentServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->app->singleton(PaymentGatewayInterface::class, function ($app) {
            return new StripePaymentGateway(config('services.stripe.secret'));
        });
    }
}

💻 Exemplo 3 — Configuração Segura e Script de Deploy

<?php
// config/services.php
return [
    'stripe' => [
        'key'    => env('STRIPE_KEY'),
        'secret' => env('STRIPE_SECRET'),
    ],
];
#!/bin/bash
# deploy.sh — otimização de produção
php artisan down
composer install --no-dev --optimize-autoloader
php artisan migrate --force
php artisan config:cache
php artisan route:cache
php artisan view:cache
php artisan event:cache
php artisan up
echo "Deploy concluído: aplicação otimizada para produção."