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

How to deal with factory boilerplate once your project gets larger?

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

现在我的表达问题是,随着您的项目变大,您的工厂样板也会增加。因此,对于每个 Action class 都有一个 ActionFactory class 与之配对以注入适当的依赖项,然后我们在发送并将其传递给我们的路由之前创建一个别名。

行动越多,工厂样板文件就越多,我想弄清楚我们如何减少该样板文件?

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

它可能会给您关于如何自己创建工厂生成器的想法。

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

可以尝试使用依赖解析器实现逻辑。 您可以通过 class 反射解决依赖关系来节省大量工厂。

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

这里需要注意避免循环依赖