Use Action class instead of Controller in Symfony

  action, symfony, symfony4

I am adherent of Action Class approach using instead of Controller. The explanation is very simple: very often Controller includes many actions, when following the Dependency Injection principle we must pass all required dependencies to a constructor and this makes a situation when the Controller has a huge number of dependencies, but in the certain moment of time (e.g. request) we use only some dependencies. It’s hard to maintain and test that spaghetti code.

To clarify, I’ve already used to work with that approach in Zend Framework 2, but there it’s named Middleware. I’ve found something similar in API-Platform, where they also use Action class instead of Controller, but the problem is that I don’t know how to cook it.

How can I obtain the next Action Class and replace standard Controller and which configuration I should add in regular Symfony project?


namespace AppActionProduct;

use AppEntityProduct;
use DoctrineORMEntityManager;
use SensioBundleFrameworkExtraBundleConfigurationMethod;
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentRoutingAnnotationRoute;

class SoftDeleteAction
     * @var EntityManager
    private $entityManager;

     * @param EntityManager $entityManager
    public function __construct(EntityManager $entityManager)
        $this->entityManager = $entityManager;

     * @Route(
     *     name="app_product_delete",
     *     path="products/{id}/delete"
     * )
     * @Method("DELETE")
     * @param Product $product
     * @return Response
    public function __invoke(Request $request, $id): Response
        $product = $this->entityManager->find(Product::class, $id);

        return new Response('', 204);

Source: Symfony Questions