# Domande Colloquio PHP Laravel Framework 2026: Eloquent, Code e Pattern Architetturali > Preparazione ai colloqui Laravel 2026: Eloquent ORM, sistemi di code, Service Container e pattern architetturali moderni con esempi di codice pratici. - Published: 2026-09-16 - Updated: 2026-09-16 - Author: Anthony Fillion-Maillet - Reading time: 5 min --- Il framework Laravel rimane nel 2026 uno dei framework PHP più utilizzati per applicazioni enterprise. Gli sviluppatori che si preparano per colloqui tecnici devono dimostrare una comprensione approfondita di Eloquent ORM, sistemi di code e pattern architetturali moderni. > Questa guida copre concetti Laravel avanzati frequentemente richiesti nei colloqui per sviluppatori senior. Ogni domanda include esempi di codice pratici e spiega i principi sottostanti. ## Eloquent ORM: Concetti Avanzati ### Qual è la differenza tra eager loading e lazy loading in Eloquent? L'eager loading risolve il problema N+1 caricando i modelli correlati in una singola query. Il lazy loading carica le relazioni solo all'accesso, causando potenziali problemi di performance. ```php // Lazy Loading - causa N+1 Queries $posts = Post::all(); foreach ($posts as $post) { echo $post->author->name; // Ogni accesso = 1 Query } // Eager Loading - solo 2 queries totali $posts = Post::with('author')->get(); foreach ($posts as $post) { echo $post->author->name; // Nessuna query aggiuntiva } // Nested Eager Loading $posts = Post::with(['author', 'comments.user'])->get(); // Conditional Eager Loading $posts = Post::with(['comments' => function ($query) { $query->where('approved', true)->orderBy('created_at', 'desc'); }])->get(); ``` ### Come si implementano le relazioni polimorfiche? Le relazioni polimorfiche permettono a un modello di appartenere a più modelli diversi. Un esempio tipico sono i commenti che possono appartenere sia a post che a video. ```php // Migration per tabella polimorfica Schema::create('comments', function (Blueprint $table) { $table->id(); $table->text('body'); $table->morphs('commentable'); // Crea commentable_type e commentable_id $table->timestamps(); }); // Comment Model class Comment extends Model { public function commentable(): MorphTo { return $this->morphTo(); } } // Post Model class Post extends Model { public function comments(): MorphMany { return $this->morphMany(Comment::class, 'commentable'); } } // Video Model class Video extends Model { public function comments(): MorphMany { return $this->morphMany(Comment::class, 'commentable'); } } // Utilizzo $post->comments()->create(['body' => 'Ottimo articolo!']); $video->comments()->create(['body' => 'Video fantastico!']); ``` ### Cosa sono gli Accessors e Mutators di Eloquent in Laravel 11+? Con Laravel 11 si utilizza il pattern `Attribute` Cast per Accessors e Mutators, offrendo una sintassi più chiara. ```php use Illuminate\Database\Eloquent\Casts\Attribute; class User extends Model { // Accessor e Mutator combinati protected function firstName(): Attribute { return Attribute::make( get: fn (string $value) => ucfirst($value), set: fn (string $value) => strtolower($value), ); } // Computed Attribute (solo Accessor) protected function fullName(): Attribute { return Attribute::make( get: fn () => "{$this->first_name} {$this->last_name}", ); } // Con caching per calcoli costosi protected function profileScore(): Attribute { return Attribute::make( get: fn () => $this->calculateProfileScore(), )->shouldCache(); } } ``` ## Sistemi di Code ed Elaborazione in Background ### Come funziona il sistema di code di Laravel? Le code di Laravel permettono di eseguire operazioni time-consuming in processi di background. Il sistema supporta diversi driver come Redis, Database e Amazon SQS. ```php // Definire una classe Job class ProcessPodcast implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; public function __construct( public Podcast $podcast, ) {} public function handle(AudioProcessor $processor): void { $processor->process($this->podcast); } // Configurazione retry public int $tries = 3; public int $backoff = 60; // Definire timeout public int $timeout = 120; // Gestione errori public function failed(Throwable $exception): void { // Inviare notifica o logging } } // Dispatch del job ProcessPodcast::dispatch($podcast); // Con ritardo ProcessPodcast::dispatch($podcast)->delay(now()->addMinutes(10)); // Su coda specifica ProcessPodcast::dispatch($podcast)->onQueue('podcasts'); ``` ### Cosa sono i Job Batches e come si utilizzano? I Job Batches permettono di raggruppare più job con tracciamento del progresso condiviso e callbacks. ```php use Illuminate\Bus\Batch; use Illuminate\Support\Facades\Bus; $batch = Bus::batch([ new ProcessPodcast($podcast1), new ProcessPodcast($podcast2), new ProcessPodcast($podcast3), ])->then(function (Batch $batch) { // Tutti i job completati con successo Log::info('Batch completed successfully'); })->catch(function (Batch $batch, Throwable $e) { // Primo errore nel batch Log::error('Batch failed', ['error' => $e->getMessage()]); })->finally(function (Batch $batch) { // Batch completato (con o senza errori) })->allowFailures()->dispatch(); // Controllare stato del batch $batch = Bus::findBatch($batchId); echo $batch->progress(); // Progresso in percentuale echo $batch->pendingJobs; // Job in attesa ``` ### Come si implementa il Rate Limiting per le code? Il Rate Limiting previene il sovraccarico di API esterne o risorse attraverso l'esecuzione controllata dei job. ```php use Illuminate\Queue\Middleware\RateLimited; use Illuminate\Support\Facades\RateLimiter; // Definire Rate Limiter (in AppServiceProvider) RateLimiter::for('api-requests', function (object $job) { return Limit::perMinute(60)->by($job->user->id); }); class SendApiRequest implements ShouldQueue { // Applicare middleware public function middleware(): array { return [new RateLimited('api-requests')]; } public function handle(): void { // Inviare richiesta API } // Rimettere job in coda se rate limited public function retryUntil(): DateTime { return now()->addHours(1); } } ``` ## Service Container e Dependency Injection ### Come funziona il Service Container di Laravel? Il Service Container è il cuore di Laravel e gestisce le dipendenze delle classi attraverso la Dependency Injection. ```php // Definire interface interface PaymentGatewayInterface { public function charge(int $amount): PaymentResult; } // Implementazione class StripePaymentGateway implements PaymentGatewayInterface { public function __construct( private string $apiKey, ) {} public function charge(int $amount): PaymentResult { // Logica Stripe } } // Binding nel ServiceProvider public function register(): void { // Simple Binding $this->app->bind(PaymentGatewayInterface::class, StripePaymentGateway::class); // Binding con configurazione $this->app->bind(PaymentGatewayInterface::class, function ($app) { return new StripePaymentGateway( apiKey: config('services.stripe.secret'), ); }); // Singleton per singola istanza $this->app->singleton(StripePaymentGateway::class); } // Utilizzo nel Controller class PaymentController extends Controller { public function __construct( private PaymentGatewayInterface $gateway, ) {} public function charge(Request $request): JsonResponse { $result = $this->gateway->charge($request->amount); return response()->json($result); } } ``` ### Cos'è il Contextual Binding? Il Contextual Binding permette implementazioni diverse a seconda del contesto di utilizzo. ```php // Implementazioni diverse per controller $this->app->when(PhotoController::class) ->needs(Filesystem::class) ->give(function () { return Storage::disk('photos'); }); $this->app->when(VideoController::class) ->needs(Filesystem::class) ->give(function () { return Storage::disk('videos'); }); // Con primitive $this->app->when(ReportGenerator::class) ->needs('$format') ->give('pdf'); ``` ## Pattern Architetturali e Best Practices ### Come si implementa il Repository Pattern in Laravel? Il Repository Pattern astrae il livello di accesso ai dati e migliora testabilità e manutenibilità. ```php // Interface interface UserRepositoryInterface { public function find(int $id): ?User; public function findByEmail(string $email): ?User; public function create(array $data): User; public function update(User $user, array $data): User; public function delete(User $user): bool; } // Implementazione Eloquent class EloquentUserRepository implements UserRepositoryInterface { public function __construct( private User $model, ) {} public function find(int $id): ?User { return $this->model->find($id); } public function findByEmail(string $email): ?User { return $this->model->where('email', $email)->first(); } public function create(array $data): User { return $this->model->create($data); } public function update(User $user, array $data): User { $user->update($data); return $user->fresh(); } public function delete(User $user): bool { return $user->delete(); } } // Classe Service utilizza Repository class UserService { public function __construct( private UserRepositoryInterface $repository, private HashManager $hash, ) {} public function registerUser(array $data): User { $data['password'] = $this->hash->make($data['password']); return $this->repository->create($data); } } ``` ### Cosa sono le Actions e come si struttura la logica di business complessa? Le Actions sono classi Single-Responsibility per operazioni di business complesse. Migliorano testabilità e riutilizzabilità. ```php class CreateOrderAction { public function __construct( private OrderRepository $orders, private InventoryService $inventory, private PaymentGatewayInterface $payment, private NotificationService $notifications, ) {} public function execute(User $user, Cart $cart, PaymentMethod $method): Order { // Verificare inventario $this->inventory->checkAvailability($cart->items); // Elaborare pagamento $paymentResult = $this->payment->charge( amount: $cart->total, method: $method, ); // Creare ordine $order = $this->orders->create([ 'user_id' => $user->id, 'total' => $cart->total, 'payment_id' => $paymentResult->id, 'items' => $cart->items->toArray(), ]); // Aggiornare inventario $this->inventory->decrementStock($cart->items); // Inviare notifiche $this->notifications->orderCreated($order); return $order; } } // Utilizzo nel Controller class OrderController extends Controller { public function store( StoreOrderRequest $request, CreateOrderAction $action, ): JsonResponse { $order = $action->execute( user: $request->user(), cart: $request->user()->cart, method: $request->paymentMethod(), ); return response()->json($order, 201); } } ``` ### Come si implementano concetti di Event Sourcing in Laravel? L'Event Sourcing memorizza i cambiamenti di stato come eventi, permettendo audit trail completi e time-travel. ```php // Definire evento class OrderPlaced { public function __construct( public string $orderId, public array $items, public int $total, public Carbon $occurredAt, ) {} } // Event Store class EventStore { public function append(string $aggregateId, object $event): void { DB::table('events')->insert([ 'aggregate_id' => $aggregateId, 'event_type' => get_class($event), 'payload' => json_encode($event), 'occurred_at' => now(), ]); } public function getEvents(string $aggregateId): Collection { return DB::table('events') ->where('aggregate_id', $aggregateId) ->orderBy('occurred_at') ->get() ->map(fn ($row) => unserialize($row->payload)); } } // Ricostruire aggregate class Order { private array $items = []; private string $status = 'pending'; public static function reconstitute(Collection $events): self { $order = new self(); foreach ($events as $event) { $order->apply($event); } return $order; } private function apply(object $event): void { match (get_class($event)) { OrderPlaced::class => $this->applyOrderPlaced($event), OrderShipped::class => $this->applyOrderShipped($event), default => null, }; } } ``` ## Conclusione I colloqui Laravel 2026 richiedono una comprensione approfondita di Eloquent ORM con le sue funzionalità avanzate come relazioni polimorfiche e il nuovo Attribute Casting. I sistemi di code con Batches e Rate Limiting sono essenziali per applicazioni scalabili. Il Service Container e la Dependency Injection formano le fondamenta per architetture testabili e manutenibili. Repository Pattern, classi Action e concetti di Event Sourcing dimostrano pensiero architetturale a livello senior. La padronanza di questi concetti con esempi di codice pratici distingue i candidati di successo dalla massa. --- Source: SharpSkill (https://sharpskill.dev), tech interview preparation for your real stack. HTML version of this page: https://sharpskill.dev/it/blog/laravel/php-laravel-framework-interview-questions-eloquent-queues-architecture