2

我是 Zend 框架的新手。有没有办法从我的活动控制器访问位于另一个模块中的模型类表?作为 ZF3 中的再见服务定位器,我无法访问位于其他模块中的模型类表。

以前在 ZF2 控制器中

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();
    ......

}

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

提前谢谢各位。再见!

4

1 回答 1

7

它在 ZF3 中的再见服务定位器

服务定位器尚未从 ZF3 中移除。但是,新版本的框架引入了一些更改,如果您依赖ServiceLocatorAwareInterface和/或将服务管理器注入到您的控制器/服务中,这些更改将破坏现有代码。

在 ZF2 中,默认操作控制器实现了此接口,并允许开发人员从控制器中获取服务管理器,就像在您的示例中一样。您可以在迁移指南中找到有关更改的更多信息。

推荐的解决方案是在服务工厂中解决控制器的所有依赖关系并将它们注入构造函数。

首先,更新控制器。

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();
    }

    // ...
}

然后创建一个新的服务工厂,将配置表依赖注入控制器(使用新的 ZF3 工厂接口

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,
],
于 2016-08-01T15:57:59.607 回答