Created
December 6, 2016 14:18
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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