php - Zf3 Controller 无法访问位于另一个模块中的模型类表

标签 php zend-framework zend-framework2 zend-controller zend-framework3

我是 Zend Framework 的新手。 有没有办法从我的事件 Controller 访问位于另一个模块中的模型类表?作为 ZF3 中的再见服务定位器,我无法访问位于其他模块中的模型类表。

以前在 ZF2 Controller 中

private configTable;

public function getConfigTable()
{
    if (!$this->configTable) {
        $sm = $this->getServiceLocator();
        $this->configTable = $sm->get('Config\Model\ConfigTable'); // <-- HERE!
    }
    return $this->configTable;
}

public function indexAction(){
     $allConfig = $this->getConfigTable()->getAllConfiguration();
    ......

}

因为服务定位器足以将函数从 Controller 调用到位于另一个模块中的模型类。 有没有办法在没有服务定位器的情况下在 ZF3 中实现类似的功能?

提前谢谢大家。 再见!

最佳答案

its bye bye service locator in ZF3

服务定位器尚未从 ZF3 中删除。但是,新版本的框架引入了一些更改,这些更改如果您依赖于 ServiceLocatorAwareInterface 和/或将服务管理器注入(inject)到您的 Controller /服务。

在 ZF2 中,默认操作 Controller 实现了这个接口(interface),并允许开发人员从 Controller 中获取服务管理器,就像在您的示例中一样。您可以在 migration guide 中找到有关更改的更多信息.

推荐的解决方案是在服务工厂内解析 Controller 的所有依赖项,并将它们注入(inject)构造函数。

首先,更新 Controller 。

namespace Foo\Controller;

use Config\Model\ConfigTable; // assuming this is an actual class name

class FooController extends AbstractActionController
{
    private $configTable;

    public function __construct(ConfigTable $configTable)
    {
        $this->configTable = $configTable;
    }

    public function indexAction()
    {
        $config = $this->configTable->getAllConfiguration();
    }

    // ...
}

然后创建一个新的服务工厂,将配置表依赖项注入(inject) Controller (使用 the new ZF3 factory interface )

namespace Foo\Controller;

use Foo\Controller\FooController;
use Interop\Container\ContainerInterface;
use Zend\ServiceManager\FactoryInterface;

class FooControllerFactory implements FactoryInterface
{
    public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
    {
        $configTable = $container->get('Config\Model\ConfigTable');

        return new FooController($configTable);
    }
}

然后更新配置以使用新工厂。

use Foo\Controller\FooControllerFactory;

'factories' => [
    'Foo\\Controller\\Foo' => FooControllerFactory::class,
],

关于php - Zf3 Controller 无法访问位于另一个模块中的模型类表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38696620/

相关文章:

mysql - Zend框架2控制台路由mysql错误

php - 从数据库中选择内容时mysql自动删除斜杠?

PHP Pagination for MySQL 数据库 - 默认显示第一页

zend-framework - Zend Mail 2.0 附件

zend-framework - 同一行中的元标记

html - 如何自定义我网站的主题取决于用户

javascript - MySQL 的多个嵌套下拉菜单

php - 使用 php 的事件当前页面不起作用

zend-framework - 将 Zend Framework 项目移至 Ubuntu 并停止工作

model-view-controller - Zend Framework 2 : Modify details of layout. Controller 中的 pthml