Skip to content

Instantly share code, notes, and snippets.

@akrabat
Created December 6, 2016 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akrabat/7a8f30658074f9759537727bb0dc67ba to your computer and use it in GitHub Desktop.
Save akrabat/7a8f30658074f9759537727bb0dc67ba to your computer and use it in GitHub Desktop.
Using ControllerPluginManager factories to inject dependencies into a controller in ZF2 and ZF3
<?php
// Using ControllerPluginManager factories to inject dependencies into
// a controller in ZF2 and ZF3
namespace My;
use Zend\Mvc\Controller\PluginManager as ControllerPluginManager;
class BookControllerFactory {
public function __invoke($container) {
// in ZF2, $container is an instance of ControllerPluginManager
// in ZF3, $container is an instance of ServiceManager
if ($container instanceof ControllerPluginManager) {
$container = $container->getServiceLocator();
// $container is now an instance of ServiceManager!
}
// This code works in both ZF2 and ZF3
$bookTable = $container->get(BookTable::class);
return new BookController($bookTable);
}
}
// module.config.php:
return [
'service_manager' => [
'factories' => [
// model configuration in the main service manager
BookTable::class => BookTableFactory::class,
],
],
'controllers' => [
'factories' => [
// controller config in the "controllers" service manager
BookController::class => BookControllerFactory::class
],
],
];
echo PHP_EOL;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment