所以我开始使用一个名为 Zend Expressive 的新框架,它是第二个基于 PSR-7 组件的框架,它应该允许您快速启动和运行代码。
现在我对表达的问题是,随着你的项目变得越来越大,你的工厂样板也会增加。因此,对于每个Action
类,都有一个ActionFactory
与之配对的类来注入适当的依赖项,然后我们在调度之前创建一个别名并将其传递给我们的路由。
动作越多,工厂样板就越多,我想弄清楚我们如何减少那个样板?
正如我在评论中所说,我认为创建工厂没有通用的解决方案。我知道你不使用 zend-servicemanager,但它带有一个 cli 命令来生成工厂类:https ://docs.zendframework.com/zend-servicemanager/console-tools/#generate-factory-for-class
它可能会为您提供有关如何自己创建工厂生成器的想法。
这是一篇关于它的文章:http: //www.masterzendframework.com/simple-factory-generation-with-factorycreator/
可以尝试使用依赖解析器来实现逻辑。您可以通过使用类反射解决依赖关系来节省大量工厂。
$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.
}
这里需要小心避免循环依赖。