stand with ukraine
mandarinian.io
search

Symfony best practices

Event listeners and subscribers

Always prefer Subscribers instead of Event Listeners.

Reasons:
  • Event Listeners must be explicitly configured in config file in order to add tag and set event to listen to.
  • Subscriber can define to which event to subscribe inside of class method EventSubscriberInterface::getSubscribedEvents .
  • Listener method names are build by convention (onKernelException), which is not obvious behavior.

You should use Event Listener only for 3rd party code and if you have option to choose, which event to listen for.

Make services private by default

You don't need access to Service Container directly, so mark each service as public: false in order to restrict access to them directly and inject them in appropriate places only.

Controllers

Keep thin controllers and implement all domain-related logic inside dedicated services. If possible try not to extend AbstractController in order not to couple with a framework (conflicts with Symfony best practices). You can use kernel.view event to transform custom response object to Symfony Response. Suffix Action is not required for controller method names.

Do not use Service Container directly

Do not use $container->get() to fetch services from container. You should configure DI container to inject required services and values to the appropriate services via Dependency Injection.

Symfony Form

Do not use Symfony Forms with entities. Use DTO instead.

Tags:#Symfony , #PHP