mercredi 7 novembre 2018

Constructor injection vs method arguments injection

I have some questions about Constructor injection vs invoke method injection.
The main question is : [According to which criteria we could decide if a class will be injected in __invoke method or in the constructor ?]

Imagine that we have this Invokable ArtilceControler with a simple __invoke() function (Kind of ADR pattern)

class ArticleController
{ 
    private $form;

    public construct __construct(FormFactoryInterface $form)
    {
        $this->form = $form;
    }

    /**
     * @param ParamFetcherInterface $paramFetcher
     * @FOSRest\QueryParam(name="page", requirements="\d+", default="1")
     *
     * @FOSRest\View()
     */
    public function __invoke(Request $request, ParamFetcherInterface $paramFetcher)
    {
        return $this->em->getRepository(Article::class)->findAll();
    }

Some times, we need to inject arguments : objects, classes that behave like services, it could be Response, Request, ParameFetecher, MailerInterface, FormFactoryInterface, Loggerinterface, CacheItemPoolInterface, RequestStack, ContainerAwareInterface ...

I noticed, that most of the time we inject some arguments typehinted with Request object at the __invoke(Request $request... method of our controller. And most of interfaces like FormFactoryInterface are injected at the level of the constructor (after defining private properties).
1) Why we prefer injecting Request into our method ? Why they are not injected into our construtor? Are they considred as services that comes from our service container? I means is it the autowiring who is registring the Request as a new service?

2) What is the difference between RequestStack and Request from HttpFoundation, why we inject RequestStack at the level of our constructor and Request at the level of our __invoke (or any method inside our controller)?

3) For example, if we use the mailer service, ther's 2 possibility to acess to mailer: We can inject MailerInterface either in the constructor or in __invoke method. But what is the most recommended way? 4)Is it true that injecting in the method will not instantiate the injected object for another time ? So it reduce the memory using and the complexity.

Aucun commentaire:

Enregistrer un commentaire