Chris Yawman
Chris Yawman

Reputation: 80

ZF2 Get ServiceManager from Controller Plugin Factory

I'm trying to create a new Controller Plugin using a factory to inject a dependency.

public function createService(ServiceLocatorInterface $serviceLocator) {

    $services = $serviceLocator->getServiceLocator();
    /** @var \Zend\Mvc\Controller\PluginManager */

    $plugin = new MyPlugin();

    if ($services->has('my_service')) {
        $plugin->setService($services->get('my_service'));
    }

    return $plugin;
}

The problem is $services can't find 'my_service'

I've added the proper configurations in my service manager

'services' => array(
    'invokables' => array(
        'my_service' => 'Application\Service\MyService'
    )
),
'controller_plugins' => array(
    'factories' => array(
        'my_plugin' => 'Application\Controller\Plugin\Factory\MyPlugin'
    )
)

My thinking is it's a bug in the PluginManager where it isn't injecting the service manager properly.

Upvotes: 1

Views: 1206

Answers (1)

Crisp
Crisp

Reputation: 11447

I've added the proper configurations in my service manager

The key for service manager configuration is service_manager, not services which is why your invokable is not found, change the key ...

'service_manager' => array(
    'invokables' => array(
        'my_service' => 'Application\Service\MyService'
    )
),
// ...

Upvotes: 5

Related Questions