Zf3 控制器无法访问位于另一个模块中的模型 class table

Zf3 controller not able to access the model class table located in another module

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

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

}

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

在此先感谢大家。 再见!

its bye bye service locator in ZF3

服务定位器尚未从 ZF3 中删除。但是,新版本的框架引入了一些更改,这些更改将破坏现有代码 if 您依赖 ServiceLocatorAwareInterface and/or 将服务管理器注入到您的controllers/services.

在 ZF2 中,默认动作控制器实现了这个接口,并允许开发人员从控制器中获取服务管理器,就像在您的示例中一样。您可以在 migration guide.

中找到有关更改的更多信息

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

首先,更新控制器。

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

    // ...
}

然后创建一个新的服务工厂,它将配置 table 依赖项注入控制器(使用 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,
],