Created
March 9, 2016 20:28
-
-
Save Saeven/2fed3f473a5057e22167 to your computer and use it in GitHub Desktop.
Abstract controller factory test, to help the migration to zend-mvc 2.7.1 that removes the service locator entirely.
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
namespace Application\Factory\Controller; | |
use Zend\ServiceManager\AbstractFactoryInterface; | |
use Zend\ServiceManager\ServiceLocatorInterface; | |
class AbstractControllerFactory implements AbstractFactoryInterface | |
{ | |
/** | |
* Determine if we can create a service with name | |
* | |
* @param ServiceLocatorInterface $serviceLocator | |
* @param $name | |
* @param $requestedName | |
* | |
* @return bool | |
*/ | |
public function canCreateServiceWithName(ServiceLocatorInterface $serviceLocator, $name, $requestedName) | |
{ | |
list( $module, ) = explode( '\\', __NAMESPACE__, 2 ); | |
return strstr( $requestedName, $module . '\Controller') !== false; | |
} | |
/** | |
* Create service with name | |
* | |
* @param ServiceLocatorInterface $serviceLocator | |
* @param $name | |
* @param $requestedName | |
* | |
* @return mixed | |
*/ | |
public function createServiceWithName(ServiceLocatorInterface $serviceLocator, $name, $requestedName) | |
{ | |
$class = new \ReflectionClass($requestedName); | |
$parentLocator = $serviceLocator->getServiceLocator(); | |
if( $constructor = $class->getConstructor() ) | |
{ | |
if( $params = $constructor->getParameters() ) | |
{ | |
$parameter_instances = []; | |
foreach( $params as $p ) | |
{ | |
$cn = $p->getClass()->getName(); | |
$parameter_instances[] = $parentLocator->get($cn); | |
} | |
return $class->newInstanceArgs($parameter_instances); | |
} | |
} | |
return new $requestedName; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment