1
votes

In Zend Framework 3 i Have create on file in Config/autoload/myconfig.globle.php

return [
      "myvariable" => [
            "key" => "value"
      ]
];

i have access through this

$config = $this->getServiceLocator()->get('Config');

give following error:

A plugin by the name "getServiceLocator" was not found in the plugin manager Zend\Mvc\Controller\PluginManager

so now how can i access this file in Controller in Zend Framework 3.

1

1 Answers

2
votes

Many things here:

First of all, the service locator has been removed. Therefore, you have to create a factory for your controller, or use a configuration based abstract factory.

Then, your files must respect the pattern defined in application.config.php, which means global.php, *.global.php, local.php or *.local.php. In your message your config is named myconfig.globle.php instead of myconfig.global.php.

So then:

final class MyController extends AbstractActionController
{
    private $variable;

    public function __construct(string $variable)
    {
        $this->variable = $variable;
    }

    public function indexAction()
    {
        // do whatever with variable
    }
}

Also you need a config:

return [
    'controllers' => [
        'factories' => [
            MyController::class => MyControllerFactory::class,
        ],
    ],
];

Finally, let's make that MyControllerFactory class:

final class MyControllerFactory
{
    public function __invoke(Container $container) : MyController
    {
        $config = $container->get('config');
        if (!isset($config['myvariable']['key']) || !is_string($config['myvariable']['key'])) {
            throw new Exception(); // Use a specific exception here.
        }
        $variable = $config['myvariable']['key']; // 'value'
        return new MyController($variable);
    }
}

That should be about it :)