Created
May 10, 2016 15:31
-
-
Save necromant2005/9a8c5190354aefea9a9361d8b51c3821 to your computer and use it in GitHub Desktop.
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 | |
namespace Layout\ServiceManager\AbstractFactory; | |
use Interop\Container\ContainerInterface; | |
use Zend\ServiceManager\AbstractFactoryInterface; | |
use Zend\ServiceManager\ServiceLocatorInterface; | |
class Factory implements AbstractFactoryInterface | |
{ | |
const INJECTIONS = 'injections'; | |
const PARAMETERS = 'parameters'; | |
/** | |
* {@inheritdoc} | |
*/ | |
public function canCreate(ContainerInterface $container, $requestedName) | |
{ | |
return $this->canCreateServiceWithName($container, $requestedName, $requestedName); | |
} | |
/** | |
* {@inheritdoc} | |
*/ | |
public function __invoke(ContainerInterface $container, $requestedName, array $options = null) | |
{ | |
return $this->createServiceWithName($container, $requestedName, $requestedName); | |
} | |
/** | |
* {@inheritdoc} | |
*/ | |
public function canCreateServiceWithName(ServiceLocatorInterface $serviceLocator, $name, $requestedName) | |
{ | |
return class_exists($requestedName, true); | |
} | |
/** | |
* {@inheritdoc} | |
*/ | |
public function createServiceWithName(ServiceLocatorInterface $serviceLocator, $name, $requestedName) | |
{ | |
$config = $serviceLocator->get('config')['di']['instance']; | |
if (!array_key_exists($requestedName, $config)) { | |
return new $requestedName(); | |
} | |
$args = []; | |
if (array_key_exists(self::INJECTIONS, $config[$requestedName])) { | |
foreach ($config[$requestedName][self::INJECTIONS] as $injectionName) { | |
$args[] = $serviceLocator->get($injectionName); | |
} | |
} | |
if (array_key_exists(self::PARAMETERS, $config[$requestedName])) { | |
foreach ($config[$requestedName][self::PARAMETERS] as $parameterValue) { | |
$args[] = $parameterValue; | |
} | |
} | |
return new $requestedName(...$args); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment