Skip to content

Instantly share code, notes, and snippets.

@necromant2005
Created May 10, 2016 15:31
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 necromant2005/9a8c5190354aefea9a9361d8b51c3821 to your computer and use it in GitHub Desktop.
Save necromant2005/9a8c5190354aefea9a9361d8b51c3821 to your computer and use it in GitHub Desktop.
<?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