【问题标题】:getServiceLocator() in Service Layer in ZF2?ZF2 服务层中的 getServiceLocator()?
【发布时间】:2023-03-19 03:11:01
【问题描述】:

我创建了一个服务层 AbcService 以允许模块访问常见的代码行。但我需要使用数据库来提取 AbcService 中的值。所以,我需要调用 getAbcTable() 来调用 $service->getServiceLocator()。当我尝试此操作时,我收到一条错误消息,提示“调用未定义的方法 getServiceLocator()。

public function getAbcTable()
 {
     if (!$this->abcTable) {
         $sm = $this->getServiceLocator();
         $this->abcTable = $sm->get('Abc\Model\AbcTable');
     }
     return $this->abcTable;
 }

【问题讨论】:

    标签: zend-framework2 service-layer


    【解决方案1】:

    您正在尝试调用可能不存在的方法。如果您的服务中需要AbcTable,则应将其作为依赖项传入。

    Module.php 中为您的服务创建一个工厂:

    public function getServiceConfig()
    {
        return array(
            'factories' => array(
                'AbcService' => function($sm) {
                    $abcTable = $sm->get('Abc\Model\AbcTable');
    
                    $abcService = new AbcService($abcTable);
    
                    return $abcService;
                },
        );
    }
    

    并修改服务的构造函数以接受表作为参数:

    class AbcService
    {
        protected $abcTable;
    
        public function __construct($abcTable)
        {
            $this->abcTable = $abcTable;
        }
    
        // etc.
    }
    

    然后,无论您需要 AbcService 的任何地方,要么将其注入,要么从服务定位器中获取:

    public function indexAction()
    {
        $abcService = $this->getServiceLocator()->get('AbcService');
    }
    

    服务将包含表类。

    【讨论】:

    • 我收到警告“__construct() 缺少参数 1”,通知说“未定义变量:chatTable”并调用未定义方法 getServiceLocator。我完全按照你的建议做了。
    • 听起来您传递给 AbcService 构造函数的内容为空,而不是表对象,但我需要查看您的代码才能提供更多帮助。如果您无法解决,请编辑您的问题以包含此内容。
    • 我想我现在已经克服了这个问题。我有 1 个小问题。如何在服务层获取 baseUrl?因为 getRequestUri() 只能在控制器中使用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-25
    • 2013-04-03
    • 1970-01-01
    • 1970-01-01
    • 2013-02-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多