0

So I started working with a new framework called Zend Expressive which is the 2nd PSR-7 component based framework which should allow you to get code up and running fairly quick.

Now my problem with expressive is that as your project gets larger your factory boilerplate also increases. So for every Action class there's a ActionFactory class paired with it to inject the proper dependencies which we then create an alias to before we dispatch and pass that to our route.

The more action's the more factory boilerplate and I'm trying to figure out how do we cut down on that boiler plate?

exts
  • 9,788
  • 4
  • 19
  • 21
  • If you use zend-servicemanager you can use its AbstractFactoryInterface: https://xtreamwayz.com/blog/2015-12-30-psr7-abstract-action-factory-one-for-all – xtreamwayz May 09 '17 at 13:00
  • Factory boilerplate is not very verbose, and IDEs such as PhpStorm add many convenience options to speed up creation. In other words, it's not a bug, it's a feature :-D – dualmon May 09 '17 at 16:33
  • @xtreamwayz yeah, but what if you don't use zend's service manager, we need a universal solution. – exts May 10 '17 at 17:45
  • I haven't seen an universal solution for all psr containers. You can always extend your current container and copy the way zend-servicemanager is doing it. It seems a lot of work at first but usually a container is just a few lines. You get pretty fast at it after you wrote a few. And as dualmon is saying, IDEs can help out to speed up writing those. – xtreamwayz May 11 '17 at 18:52

2 Answers2

1

As I said in the comments, I don't think there is a universal solution to create factories. I know that you don't use zend-servicemanager, but it comes with a cli command to generate factory classes: https://docs.zendframework.com/zend-servicemanager/console-tools/#generate-factory-for-class

It might give you ideas on how to create a factory generator yourself.

Here's an article about it: http://www.masterzendframework.com/simple-factory-generation-with-factorycreator/

xtreamwayz
  • 1,285
  • 8
  • 10
0

Can try to implement logic with dependency resolver. You can save a lot of factories by resolving dependency with class reflection.

    $instance = null;
    $reflection = new \ReflectionClass($className);

    $constructor = $reflection->getConstructor();
    if ($constructor === null) {
        // no constructor specified, you can simply return the new instance.
        $instance = $reflection->newInstanceWithoutConstructor();
    } else {
        // if there is constructor, you can loop through the constructor parameters and build the instance.
    }

Need to be careful to avoid circular dependency here.

dontfight
  • 91
  • 1
  • 3