PHP 已弃用:您正在从 class ZFTool\Controller\ModuleController 中检索服务定位器

PHP Deprecated: You are retrieving the service locator from within the class ZFTool\Controller\ModuleController

我已经使用 composer 安装了 zend 工具

$ composer require zendframework/zftool:dev-master 

zftool 已安装,当我 运行 php /vender/bin/zf.php 模块列表时它会发出警告

PHP Deprecated: You are retrieving the service locator from within the class ZFTool\Controller\ModuleController. Please be aware that ServiceLocatorAwareInterface is deprecated and will be removed in version 3.0, along with the ServiceLocatorAwareInitializer. ...

我正在使用 Ubuntu

有几个解决方案:

  • 在您的 error_reporting 中,禁用 E_USER_DEPRECATED 报告。这个 只是掩盖了问题。
  • 固定到早期版本的 zend-mvc(例如, composer require "zendframework/zend-mvc:~2.6.0" 将固定 具体到2.6系列,不会安装2.7系列)。 再次,这只是掩盖了问题,并有可能离开你的 如果将安全补丁应用到后来的未成年人,则应用程序不安全 发布 zend-mvc。
  • 修复您的代码以不再使用 getServiceLocator()。这是推荐的路径。的方式 完成后一点是为了确保所有依赖项 您的控制器在实例化期间被注入。

这意味着:

  • 您需要为控制器创建工厂。
  • 您将需要更新您的控制器以接受之前从 getServiceLocator() 中提取的构造函数中的依赖项。 例如,假设您的控制器中有这样的东西:

$db = $this->getServiceLocator()->get('Db\ApplicationAdapter');

您可以按如下方式更改代码:

  • $db 属性 添加到您的 class。
  • 更新您的构造函数以接受数据库适配器,并将其分配给 属性。
  • 将上面的行更改为简单的 $db = $this->db(或者只使用 属性!)
  • 为您的控制器添加一个工厂,如果当前不存在的话。

所以:

use Zend\Db\Adapter\AdapterInterface;
use Zend\Mvc\Controller\AbstractActionController;

class YourController extends AbstractActionController
{
    private $db;

    public function __construct(AdapterInterface $db)
    {
        $this->db = $db;
    }

    public function someAction()
    {
        $results = $this->db->query(/* ... */);
        /* ... */
    }
}

你的工厂看起来像这样:

class YourControllerFactory
{
    public function __invoke($container)
    {
        return new YourController($this->get('Db\ApplicationAdapter'));
    }
}

在您的应用程序或模块配置中,您会将此工厂映射到您的控制器:

return [
    'controllers' => [
        'factories' => [
            YourController::class => YourControllerFactory::class,
        /* ... */
        ],
        /* ... */
    ],
    /* ... */
];
];

这似乎有很多步骤。但是,它确保您的代码没有隐藏的依赖关系,提高代码的可测试性,并允许您通过配置做一些很酷的事情,比如替代方案。