Skip to content

Instantly share code, notes, and snippets.

@Saeven
Created March 9, 2016 20:28
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 Saeven/2fed3f473a5057e22167 to your computer and use it in GitHub Desktop.
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.
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