Skip to content
Tutorials Center
My learning

Topics

Lesson 61 of 62 ยท Practice and Review

Symfony Interview Questions

Prepare for a Symfony interview with clear answers on the container, kernel events, Doctrine, security, Messenger and the pitfalls interviewers love to ask about.

Interviewers rarely ask you to recite documentation. They ask why things work the way they do: why a service is shared, what happens between the front controller and your controller, why flush() matters, which side of a relation owns the foreign key. This lesson collects the questions that come up most often, with answers short enough to say out loud and deep enough to survive a follow-up.

The answers target Symfony 7.x. Real framework code is read-only on this site, so the code blocks are for reading. Three runnable plain-PHP stand-ins let you check the ideas that are easiest to get wrong: shared services, event priorities and the N+1 query problem. Each answer links to the lesson where the topic is taught properly.

The container and dependency injection

What is the service container? It is the object that knows how to build your services and hands out the same instance on every request for it. You declare services (usually just by placing classes in src/), Symfony autowires their constructors and compiles everything into plain PHP before the application serves a request. See Services and the Service Container.

Are services singletons? By default they are shared: the container builds a service once per kernel boot and returns that instance to everyone who needs it. This is not the Singleton pattern, because nothing in the class enforces it; a different container (or shared: false) would give you a new object each time. Services are also private by default, which means you inject them instead of calling $container->get().

PHP Shared services: one instance per container

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

How does autowiring choose a service? By the constructor parameter's type-hint. A class resolves to the service with that id; an interface needs an alias (created automatically when exactly one implementation exists). Scalars are never guessed: use #[Autowire], bind or arguments. Everything is resolved at compile time, so mistakes fail early. See Autowiring and Dependency Injection.

What are tags, decorators and compiler passes for? Tags group services so another service can receive them all (#[AutowireIterator]). A decorator wraps an existing service and replaces it everywhere without touching the original. A compiler pass is code that inspects and edits the container definitions while it compiles; bundles use them to collect tagged services. See Tags, Decorators and Service Locators and Compiler Passes and Bundle Extensions.

Why is injecting the whole container a bad idea? It hides dependencies, makes tests harder and turns compile-time errors into runtime errors. Inject exactly what you need. When you must choose among many services at runtime, inject a service locator limited to the services you list.

The HttpKernel and events

What happens between the request and the response? public/index.php creates the kernel, which turns the Request into a Response by dispatching events: the router picks a controller, argument resolvers build its arguments, your controller runs, and listeners can change the response before it is sent. After the response leaves, kernel.terminate fires. See From Request to Response.

flowchart LR
    A["kernel.request<br/>(routing, firewall)"] --> B["kernel.controller"]
    B --> C["kernel.controller_arguments"]
    C --> D["Controller runs"]
    D --> E{"Returned a Response?"}
    E -->|no| F["kernel.view"]
    E -->|yes| G["kernel.response"]
    F --> G
    G --> H["Response sent"]
    H --> I["kernel.terminate"]
    D -.->|"exception"| X["kernel.exception"]
    X --> G

The main kernel events in order; kernel.exception turns an error into a response, which still passes through kernel.response.

Listener or subscriber? Both react to events. A listener is registered with a method name (#[AsEventListener] is the usual way today); a subscriber declares its events in a static method. Pick whichever reads better. Higher priority numbers run first, the default is 0, and stopPropagation() prevents later listeners from running. See Events and Listeners.

PHP Priorities and stopPropagation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

How do you handle exceptions globally? Listen to kernel.exception and set a response on the event, or customize the error templates. For APIs, an exception listener that returns JSON keeps controllers free of try/catch.

Doctrine

What do persist() and flush() do? persist($entity) only tells the entity manager to manage a new object. Nothing is written until flush(), which computes the changes recorded by the unit of work and runs the SQL inside one transaction. Managed entities that you modify are updated on flush() without another persist(). See Entities and Mapping.

What is the owning side of a relation? The side that holds the foreign key. In a bidirectional OneToMany/ManyToOne pair the ManyToOne side (the "many") always owns the relation, and the OneToMany side is the inverse, declared with mappedBy. Doctrine only looks at the owning side when saving, so setting only the inverse side silently stores nothing. See Relations.

What is the N+1 problem and how do you fix it? Loading N parents and then touching a lazy relation on each runs 1 + N queries. Fix it with a fetch join in DQL or the QueryBuilder (addSelect + leftJoin), or by loading related rows with a single IN query. See Doctrine Performance and Pitfalls.

PHP Counting queries: N+1 versus one join

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

When would you use DBAL or raw SQL instead of the ORM? For reports, bulk updates and heavy aggregates, where hydrating thousands of objects wastes memory. The ORM shines for domain logic on a few objects at a time. See Repositories and Queries.

Why should migrations be reviewed before running in production? The diff is generated from the mapping and cannot know your data. A renamed column looks like a drop plus an add, and adding a NOT NULL column to a filled table needs a default or a multi-step change. See Migrations.

Security

What is the difference between authentication and authorization in Symfony? Authentication answers who are you? and is done by the firewall's authenticators, which produce a user (a UserBadge) and credentials. Authorization answers may you do this? and is checked with access_control, #[IsGranted] and voters. See Security: Users and Firewalls.

What is a firewall? A named section of security.yaml that matches requests by pattern and defines how users authenticate there (form login, JSON login, access token, custom authenticator). Only one firewall handles a request, and it is picked by the first matching pattern. Order matters, and the dev firewall with security: false must come before the main one.

What is a voter and why use one? A class that answers one question: "may this user perform this attribute on this subject?" It keeps rules such as "only the author may edit a post" in one tested place instead of repeated in controllers and templates. See Authorization: Roles and Voters.

How are passwords stored? Never in plain text. Inject UserPasswordHasherInterface, call hashPassword() when saving, and let the auto algorithm pick the best one. Symfony can rehash on login when the algorithm improves.

Which access_control rule wins? The first one that matches the path (and optionally host, method or IP) decides; later rules are not checked. Put specific paths before general ones.

Messenger

What problem does Messenger solve? It separates deciding that something must happen from doing it. You dispatch a small message object, a handler does the work, and a routing rule decides whether this happens immediately or on a queue consumed by a worker. See Messenger: Messages and Handlers.

flowchart LR
    C["Controller"] -->|"dispatch(message)"| B["Message bus"]
    B -->|"sync route"| H["Handler"]
    B -->|"async route"| T[("Transport<br/>(queue)")]
    T --> W["messenger:consume<br/>(worker)"]
    W --> H
    W -.->|"retries exhausted"| F[("Failure transport")]

Routing decides whether a message is handled in-process or sent to a queue for a worker.

What should a message contain? Plain data such as ids and scalars. Never put a Doctrine entity in a message: it is serialized, may be stale when the worker runs, and can fail to unserialize. Send the id and let the handler load fresh data.

What happens when a handler fails? For async transports Symfony retries with a delay that grows between attempts (three retries by default). When retries are exhausted the message goes to the failure transport, where you can inspect it with messenger:failed:show and requeue it with messenger:failed:retry. Throw UnrecoverableMessageHandlingException to skip retries.

Why must workers be restarted after a deploy? A worker is a long-running PHP process that keeps the old code and container in memory. Run messenger:stop-workers (or let your supervisor restart them) after deploying.

Common pitfalls

These are the traps that separate a candidate who has built a Symfony application from one who has only read about it:

  • Forgetting flush(). Nothing reaches the database until it runs.
  • Updating only the inverse side of a relation.
  • Calling $container->get() (or the container argument) instead of injecting dependencies.
  • Business logic in controllers. Extract services; controllers should translate HTTP to method calls and back. See Controllers in Depth.
  • Committing secrets. .env is a committed default file; real secrets belong in .env.local, the secrets vault or the server environment. See Environment Variables and Secrets.
  • Deploying in dev mode. Production needs APP_ENV=prod, APP_DEBUG=0, a warmed cache and optimized autoloading.
  • Using a closed entity manager. After a database exception inside flush(), the entity manager is closed and must be reset.
  • Trusting form data without validation, or exposing entities directly in API responses so that private fields leak.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In a bidirectional OneToMany/ManyToOne relation, which side owns the relation?

    The ManyToOne side stores the foreign key column and is the owning side. Doctrine reads only the owning side when persisting, so set it even if you also keep the inverse collection in sync.
  2. 2. What does stopPropagation() on an event do?

    Listeners are called in priority order; after stopPropagation() the dispatcher skips the remaining ones. It does not cancel the request by itself.
  3. 3. Why should a Messenger message carry an entity id instead of the entity?

    A queued message may run minutes later. An entity inside it can be stale or fail to unserialize, while an id lets the handler load the current state.
  4. 4. A page lists 50 posts and shows each post's author name, and the profiler reports 51 queries. What is this and what is the usual fix?

    One query for the posts plus one lazy query per author is the N+1 pattern. A join that selects the authors together with the posts brings it back to one query.
  5. 5. Which statement about services in Symfony is correct?

    Services are shared and private by default, and the App\ resource in services.yaml registers every class in src/ automatically.

Summary

  • Services are shared, private and autowired by type; errors surface when the container compiles.
  • The kernel turns a request into a response through events; priority controls order and stopPropagation() ends the chain.
  • Doctrine writes on flush(); the many side of a relation owns it; fetch joins cure N+1.
  • Firewalls authenticate, access_control and voters authorize, and the first matching rule wins.
  • Messenger messages carry ids, retry with delays and land in a failure transport; restart workers after deploys.
  • Most pitfalls come from forgetting flush(), skipping validation, committing secrets and deploying with dev settings.

Finish with the one-page reference in the Symfony Cheat Sheet.