首页 > 解决方案 > 如何将服务管理器注入 Zend Framework 3 中的模型文件

问题描述

我刚刚将一个项目从 ZF 1.x 版本升级到 Zend Framework 3。

在 ZF 1.x 版本中,我们实现了一个功能,例如为使用 Zend Registry 组件在应用程序中发出的请求提供唯一 id,这在 ZF 3 中不存在。我正在尝试使用 ServiceManager 实现该功能。

所以我尝试通过创建一个工厂类将 ServiceManager 注入模型文件,如下所示:

我的模型类文件代码:

<?php

namespace Application\Model\Common;

use Application\Model\Common\Config\BaseConfig;
use Zend\Session\Container;
use \Zend\ServiceManager\ServiceManager;

class CommonUtils  extends BaseConfig{    

    public function __construct(ServiceManager $sm) {
        echo '<pre>';
        print_r($sm);
        exit();
    }

}

?>

工厂类代码:

namespace Application\Model\Common;

use Zend\ServiceManager\Factory\FactoryInterface;
use Interop\Container\ContainerInterface;

class CommonUtilsFactory implements FactoryInterface{
    //put your code here
    public function __invoke(ContainerInterface $container, $requestedName, mixed $options = null) {
        $serviceManager = $container->get('ServiceManager');
        return new CommonUtils($serviceManager);
    }
}

更新 module.config.php 文件如下:

    /** SERVICE MANAGER CONFIGURATION - STARTS HERE **/
    'service_manager' => [
        'factories' => [
            CommonUtils::class => \Application\Model\Common\CommonUtilsFactory::class
        ],

        // Make an alias so that we can use it where we need
        'aliases' => [
        ],
    ],
    /** SERVICE MANAGER CONFIGURATION - ENDS HERE **/

但它不起作用并给出以下错误。

可捕获的致命错误:传递给 Application\Model\Common\CommonUtils::__construct() 的参数 1 必须是 Zend\ServiceManager\ServiceManager 的实例,没有给出

有人请在这里帮助我了解如何在 Zend Framework 3 的模型文件中访问/注入 ServiceManager。

提前致谢。

标签: phpzend-framework2zend-framework3zend-servicemanager

解决方案


推荐阅读