Use Action class instead of Controller in Symfony

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.

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

<?php
declare(strict_types=1);

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);
        $product->delete();
        $this->entityManager->flush();

        return new Response('', 204);
    }
}

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *