一旦项目变大,如何处理工厂样板?

时间:2017-05-08 17:17:12

标签: php zend-expressive

所以我开始使用一个名为Zend Expressive的新框架,这是第二个基于PSR-7组件的框架,它可以让你快速获得代码并运行。

现在我表达的问题是随着你的项目变大,你的工厂样板也会增加。因此,对于每个Action类,都有一个ActionFactory类与它配对,以便注入正确的依赖关系,然后在我们调度并将其传递给路径之前创建一个别名。

行动越多,工厂样板越多,我想弄清楚我们如何减少锅炉板?

2 个答案:

答案 0 :(得分:1)

正如我在评论中所说,我不认为创建工厂有一个通用的解决方案。我知道你不使用zend-servicemanager,但它带有一个cli命令来生成工厂类:https://docs.zendframework.com/zend-servicemanager/console-tools/#generate-factory-for-class

它可能会为您提供有关如何自己创建工厂生成器的想法。

这是一篇关于它的文章:http://www.masterzendframework.com/simple-factory-generation-with-factorycreator/

答案 1 :(得分:0)

可以尝试使用依赖项解析器实现逻辑。 您可以通过使用类反射来解决依赖性来保存大量工厂。

    $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.
    }

这里需要小心避免循环依赖。