dongza3124 2013-06-27 11:03
浏览 35
已采纳

在zf2项目的任何地方调用服务,工厂

I am a newbie to zend framework. I am worrying how to call a service,factory other than from a controller (or class which is not extended AbstractActionController).

I am using the ZfcUser module to authenticate users. Now I want to check wheather a user logged or not inside the ZfcUser\Form\Base class. I am unable to call the zfcUserAuthentication factory which inside the getControllerPluginConfig() in ZfcUser\Module

Please some one help me.

Thank you

  • 写回答

2条回答 默认 最新

  • dtlygweb2017 2013-06-27 11:35
    关注

    What you are looking at is the concept of Dependency Injection. Basically YOU need to make sure that the Services you create GAIN access to the Gateways or Services they need.

    For example, if you have a Service that takes care about persisting your Entities (DataObjects) to the Database, then YOU need to make sure to "inject" the Database-Adapter into the ServiceObject.

    Required Dependencies therefore should be set via Constructor injection, i.e.:

    class MyService {
        public function __construct(DbAdapter $dbA) {
            // do stuff with $dbA
        }
    }
    

    And you create this via the ServiceManager

    'service_manager' => array(
        'factories' => array(
            'MyService' => function($sm) {
                 $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
                 $service   = new MyService($dbAdapter);
                 return $service;
             }
        )
    )
    

    And lastly you access your service via the ServiceManager (probably somewhere in your controller).

    public function someAction() {
        $service = $this->getServiceLocator()->get('MyService');
        // do stuff with $service
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊