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

走远了吗. 提交于 2019-12-06 10:39:19

its bye bye service locator in ZF3

The service locator has not been removed from ZF3. However, the new version of the framework has introduced some changes that will break existing code if you have relied on the ServiceLocatorAwareInterface and/or having the service manager injected into your controllers/services.

In ZF2 The default action controller implemented this interface and allowed developers to fetch the service manager from within the controller, just like in your example. You can find more information on the changes in the migration guide.

The recommended solution to this is to resolve all the dependencies of your controller within a service factory and inject them into the constructor.

Firstly, update the 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();
    }

    // ...
}

Then create a new service factory that will inject the config table dependency into the controller (using 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);
    }
}

Then update the configuration to use the new factory.

use Foo\Controller\FooControllerFactory;

'factories' => [
    'Foo\\Controller\\Foo' => FooControllerFactory::class,
],
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!