dqfwcj0030 2013-12-06 16:26
浏览 12
已采纳

在类中使用工厂而不在ZF2中注入整个服务管理器

I have a class called classB which has multiple dependencies which I am setting up using ClassBFactory. Inside classA I would like to create a new instance of classB using the classBFactory.

Is the only way to get a new instance of classB from its factory by injecting the whole service container into classA, or is there another way? It would seem bad practice to pass in the whole service container as this would give the class access to a lot more than needed.

I've experimented with the following but this won't work as createService() requires the service container, which I would rather not inject into classA

class ClassA {
    protected $classBFactory;
    public function __construct(ClassBFactory $classBFactory)
    {
        $this->classBFactory = $classBFactory;
    }

    public function getNewA()
    {
        return $this->classBFactory->createService();
    }
}
  • 写回答

1条回答 默认 最新

  • douzi2785 2013-12-06 18:39
    关注

    Just create a factory for classA as well where you inject classB into classA. In your factory pull ClassB from the service locator and inject it with contructor injection into ClassA. You should really try to not let your classes depend on the serviceLocator for various reasons, but only let your factories pull from the servicelocator and inject those dependencies with constructor or setter injection (this is called inversion of control).

    ClassA

    class ClassA {
        protected $classB;
        public function __construct(ClassB $classB)
        {
            $this->classB = $classB;
        }
    }
    

    Module.php

    public function getServiceConfig()
    {
        return array(
            'factories' => array(
                'MyNamespace\ClassA' => function($sm) {
                    return new ClassA($sm->get('MyNamespace\ClassB'));
                }, //Using a closure here, but it's better to create a seperate factory class
                'MyNamespace\ClassB' => 'MyNamespace\Factory\ClassBFactory'
            )
        )
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?