Removing the need for ActionFactories


#1

Hi,

I’m studying expressive and DI, maybe my question is a noob one. But here is what I don’t understand:

Every Action that expects something is its constructor needs a factory, right? So you can get the instance of what you want and instantiate the action class with it. For example:

class HomePageFactory
{
    public function __invoke(ContainerInterface $container)
    {
        $router   = $container->get(RouterInterface::class);
        $template = $container->has(TemplateRendererInterface::class)
            ? $container->get(TemplateRendererInterface::class)
            : null;
        return new HomePageAction($router, $template);
    }
}

Is it really necessary? Can’t I simply $container->get($action) in the DispacherMiddleware and eliminate the need for the factory? Isn’t what LazyLoadingMiddlewareis doing?


#2

Usually, a reflection factory suffices:

Marco Pivetta

http://twitter.com/Ocramius

http://ocramius.github.com/


#3

I saw that it’s a zend-servicemanager class. I’m using auryn. Shouldn’t be something as common as it to be part of the expressive itself to eliminate the boilerplate code by default?


#4

Every DIC decides on its own: the defaults of Auryn should be
reflection-based anyway, so why are you even using a factory?


#5

Funny you should say that; I asked for help with this in Slack a few weeks ago. :smile:

This sort of thing isn’t necessary with every container, as @ocramius notes; for containers that use reflection natively (Auryn, php-di, etc.), you do not need to create factories if they can resolve all dependencies for you. For the others, yes, you need to create a factory, and tooling such as what I’ve proposed in the above link will assist.