Skip to content

[DependencyInjection] Add a new Syntax to define factories as callables #12008

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Sep 24, 2014
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions UPGRADE-3.0.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,13 @@ UPGRADE FROM 2.x to 3.0
$table->render();
```

### DependencyInjection

* The methods `Definition::setFactoryClass()`,
`Definition::setFactoryMethod()`, and `Definition::setFactoryService()` have
been removed in favor of `Definition::setFactory()`. Services defined using
YAML or XML use the same syntax as configurators.

### EventDispatcher

* The interface `Symfony\Component\EventDispatcher\Debug\TraceableEventDispatcherInterface`
Expand Down
5 changes: 5 additions & 0 deletions src/Symfony/Component/DependencyInjection/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
CHANGELOG
=========

2.6.0
-----

* added new factory syntax and deprecated the old one

2.5.0
-----

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,9 @@ public function process(ContainerBuilder $container)
if ($definition->getConfigurator()) {
$this->processArguments(array($definition->getConfigurator()));
}
if ($definition->getFactory()) {
$this->processArguments(array($definition->getFactory()));
}
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,28 +42,22 @@ public function process(ContainerBuilder $container)
foreach ($container->getDefinitions() as $id => $definition) {
// synthetic service is public
if ($definition->isSynthetic() && !$definition->isPublic()) {
throw new RuntimeException(sprintf(
'A synthetic service ("%s") must be public.',
$id
));
throw new RuntimeException(sprintf('A synthetic service ("%s") must be public.', $id));
}

// synthetic service has non-prototype scope
if ($definition->isSynthetic() && ContainerInterface::SCOPE_PROTOTYPE === $definition->getScope()) {
throw new RuntimeException(sprintf(
'A synthetic service ("%s") cannot be of scope "prototype".',
$id
));
throw new RuntimeException(sprintf('A synthetic service ("%s") cannot be of scope "prototype".', $id));
}

if ($definition->getFactory() && ($definition->getFactoryClass() || $definition->getFactoryService() || $definition->getFactoryMethod())) {
throw new RuntimeException(sprintf('A service ("%s") can use either the old or the new factory syntax, not both.', $id));
}

// non-synthetic, non-abstract service has class
if (!$definition->isAbstract() && !$definition->isSynthetic() && !$definition->getClass()) {
if ($definition->getFactoryClass() || $definition->getFactoryService()) {
throw new RuntimeException(sprintf(
'Please add the class to service "%s" even if it is constructed by a factory '
.'since we might need to add method calls based on compile-time checks.',
$id
));
if ($definition->getFactory() || $definition->getFactoryClass() || $definition->getFactoryService()) {
throw new RuntimeException(sprintf('Please add the class to service "%s" even if it is constructed by a factory since we might need to add method calls based on compile-time checks.', $id));
}

throw new RuntimeException(sprintf(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,9 +64,10 @@ public function process(ContainerBuilder $container)
);

$configurator = $this->inlineArguments($container, array($definition->getConfigurator()));
$definition->setConfigurator(
$configurator[0]
);
$definition->setConfigurator($configurator[0]);

$factory = $this->inlineArguments($container, array($definition->getFactory()));
$definition->setFactory($factory[0]);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,9 @@ private function resolveDefinition($id, DefinitionDecorator $definition)
if (isset($changes['factory_service'])) {
$def->setFactoryService($definition->getFactoryService());
}
if (isset($changes['factory'])) {
$def->setFactory($definition->getFactory());
}
if (isset($changes['configurator'])) {
$def->setConfigurator($definition->getConfigurator());
}
Expand Down
31 changes: 31 additions & 0 deletions src/Symfony/Component/DependencyInjection/Definition.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ class Definition
{
private $class;
private $file;
private $factory;
private $factoryClass;
private $factoryMethod;
private $factoryService;
Expand Down Expand Up @@ -56,6 +57,30 @@ public function __construct($class = null, array $arguments = array())
$this->arguments = $arguments;
}

/**
* Sets a factory.
*
* @param string|array $factory A PHP function or an array containing a class/Reference and a method to call
*
* @return Definition The current instance
*/
public function setFactory($factory)
{
$this->factory = $factory;

return $this;
}

/**
* Gets the factory.
*
* @return string|array The PHP function or an array containing a class/Reference and a method to call
*/
public function getFactory()
{
return $this->factory;
}

/**
* Sets the name of the class that acts as a factory using the factory method,
* which will be invoked statically.
Expand All @@ -65,6 +90,7 @@ public function __construct($class = null, array $arguments = array())
* @return Definition The current instance
*
* @api
* @deprecated Deprecated since version 2.6, to be removed in 3.0.
*/
public function setFactoryClass($factoryClass)
{
Expand All @@ -79,6 +105,7 @@ public function setFactoryClass($factoryClass)
* @return string|null The factory class name
*
* @api
* @deprecated Deprecated since version 2.6, to be removed in 3.0.
*/
public function getFactoryClass()
{
Expand All @@ -93,6 +120,7 @@ public function getFactoryClass()
* @return Definition The current instance
*
* @api
* @deprecated Deprecated since version 2.6, to be removed in 3.0.
*/
public function setFactoryMethod($factoryMethod)
{
Expand Down Expand Up @@ -142,6 +170,7 @@ public function getDecoratedService()
* @return string|null The factory method name
*
* @api
* @deprecated Deprecated since version 2.6, to be removed in 3.0.
*/
public function getFactoryMethod()
{
Expand All @@ -156,6 +185,7 @@ public function getFactoryMethod()
* @return Definition The current instance
*
* @api
* @deprecated Deprecated since version 2.6, to be removed in 3.0.
*/
public function setFactoryService($factoryService)
{
Expand All @@ -170,6 +200,7 @@ public function setFactoryService($factoryService)
* @return string|null The factory service id
*
* @api
* @deprecated Deprecated since version 2.6, to be removed in 3.0.
*/
public function getFactoryService()
{
Expand Down
10 changes: 10 additions & 0 deletions src/Symfony/Component/DependencyInjection/DefinitionDecorator.php
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,16 @@ public function setClass($class)
return parent::setClass($class);
}

/**
* {@inheritdoc}
*/
public function setFactory($callable)
{
$this->changes['factory'] = true;

return parent::setFactory($callable);
}

/**
* {@inheritdoc}
*
Expand Down
35 changes: 33 additions & 2 deletions src/Symfony/Component/DependencyInjection/Dumper/PhpDumper.php
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,7 @@ private function addServiceLocalTempVariables($cId, $definition)
$this->getServiceCallsFromArguments($iDefinition->getMethodCalls(), $calls, $behavior);
$this->getServiceCallsFromArguments($iDefinition->getProperties(), $calls, $behavior);
$this->getServiceCallsFromArguments(array($iDefinition->getConfigurator()), $calls, $behavior);
$this->getServiceCallsFromArguments(array($iDefinition->getFactory()), $calls, $behavior);
}

$code = '';
Expand Down Expand Up @@ -523,6 +524,17 @@ private function addService($id, $definition)
$return[] = '@throws RuntimeException always since this service is expected to be injected dynamically';
} elseif ($class = $definition->getClass()) {
$return[] = sprintf("@return %s A %s instance.", 0 === strpos($class, '%') ? 'object' : "\\".$class, $class);
} elseif ($definition->getFactory()) {
$factory = $definition->getFactory();
if (is_string($factory)) {
$return[] = sprintf('@return object An instance returned by %s().', $factory);
} elseif (is_array($factory) && (is_string($factory[0]) || $factory[0] instanceof Definition || $factory[0] instanceof Reference)) {
if (is_string($factory[0]) || $factory[0] instanceof Reference) {
$return[] = sprintf('@return object An instance returned by %s::%s().', (string) $factory[0], $factory[1]);
} elseif ($factory[0] instanceof Definition) {
$return[] = sprintf('@return object An instance returned by %s::%s().', $factory[0]->getClass(), $factory[1]);
}
}
} elseif ($definition->getFactoryClass()) {
$return[] = sprintf('@return object An instance returned by %s::%s().', $definition->getFactoryClass(), $definition->getFactoryMethod());
} elseif ($definition->getFactoryService()) {
Expand Down Expand Up @@ -701,7 +713,25 @@ private function addNewInstance($id, Definition $definition, $return, $instantia
$arguments[] = $this->dumpValue($value);
}

if (null !== $definition->getFactoryMethod()) {
if (null !== $definition->getFactory()) {
$callable = $definition->getFactory();
if (is_array($callable)) {
if ($callable[0] instanceof Reference
|| ($callable[0] instanceof Definition && $this->definitionVariables->contains($callable[0]))) {
return sprintf(" $return{$instantiation}%s->%s(%s);\n", $this->dumpValue($callable[0]), $callable[1], $arguments ? implode(', ', $arguments) : '');
}

$class = $this->dumpValue($callable[0]);
// If the class is a string we can optimize call_user_func away
if (strpos($class, "'") === 0) {
return sprintf(" $return{$instantiation}\%s::%s(%s);\n", substr($class, 1, -1), $callable[1], $arguments ? implode(', ', $arguments) : '');
}

return sprintf(" $return{$instantiation}call_user_func(array(%s, '%s'), %s);\n", $this->dumpValue($callable[0]), $callable[1], $arguments ? ', '.implode(', ', $arguments) : '');
}

return sprintf(" $return{$instantiation}%s(%s);\n", $callable, $arguments ? implode(', ', $arguments) : '');
} elseif (null !== $definition->getFactoryMethod()) {
if (null !== $definition->getFactoryClass()) {
$class = $this->dumpValue($definition->getFactoryClass());

Expand Down Expand Up @@ -1116,7 +1146,8 @@ private function getInlinedDefinitions(Definition $definition)
$this->getDefinitionsFromArguments($definition->getArguments()),
$this->getDefinitionsFromArguments($definition->getMethodCalls()),
$this->getDefinitionsFromArguments($definition->getProperties()),
$this->getDefinitionsFromArguments(array($definition->getConfigurator()))
$this->getDefinitionsFromArguments(array($definition->getConfigurator())),
$this->getDefinitionsFromArguments(array($definition->getFactory()))
);

$this->inlinedDefinitions->offsetSet($definition, $definitions);
Expand Down
11 changes: 11 additions & 0 deletions src/Symfony/Component/DependencyInjection/Dumper/XmlDumper.php
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,17 @@ private function addService($definition, $id, \DOMElement $parent)

$this->addMethodCalls($definition->getMethodCalls(), $service);

if ($callable = $definition->getFactory()) {
$factory = $this->document->createElement('factory');
if (is_array($callable)) {
$factory->setAttribute($callable[0] instanceof Reference ? 'service' : 'class', $callable[0]);
$factory->setAttribute('method', $callable[1]);
} else {
$factory->setAttribute('function', $callable);
}
$service->appendChild($factory);
}

if ($callable = $definition->getConfigurator()) {
$configurator = $this->document->createElement('configurator');
if (is_array($callable)) {
Expand Down
34 changes: 25 additions & 9 deletions src/Symfony/Component/DependencyInjection/Dumper/YamlDumper.php
Original file line number Diff line number Diff line change
Expand Up @@ -147,16 +147,12 @@ private function addService($id, $definition)
}
}

if ($callable = $definition->getConfigurator()) {
if (is_array($callable)) {
if ($callable[0] instanceof Reference) {
$callable = array($this->getServiceCall((string) $callable[0], $callable[0]), $callable[1]);
} else {
$callable = array($callable[0], $callable[1]);
}
}
if ($callable = $definition->getFactory()) {
$code .= sprintf(" factory: %s\n", $this->dumper->dump($this->dumpCallable($callable), 0));
}

$code .= sprintf(" configurator: %s\n", $this->dumper->dump($callable, 0));
if ($callable = $definition->getConfigurator()) {
$code .= sprintf(" configurator: %s\n", $this->dumper->dump($this->dumpCallable($callable), 0));
}

return $code;
Expand Down Expand Up @@ -222,6 +218,26 @@ private function addParameters()
return $this->dumper->dump(array('parameters' => $parameters), 2);
}

/**
* Dumps callable to YAML format
*
* @param callable $callable
*
* @return callable
*/
private function dumpCallable($callable)
{
if (is_array($callable)) {
if ($callable[0] instanceof Reference) {
$callable = array($this->getServiceCall((string) $callable[0], $callable[0]), $callable[1]);
} else {
$callable = array($callable[0], $callable[1]);
}
}

return $callable;
}

/**
* Dumps the value to YAML format
*
Expand Down
15 changes: 15 additions & 0 deletions src/Symfony/Component/DependencyInjection/Loader/XmlFileLoader.php
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,21 @@ private function parseDefinition($id, \DOMElement $service, $file)
$definition->setArguments($this->getArgumentsAsPhp($service, 'argument'));
$definition->setProperties($this->getArgumentsAsPhp($service, 'property'));

if ($factories = $this->getChildren($service, 'factory')) {
$factory = $factories[0];
if ($function = $factory->getAttribute('function')) {
$definition->setFactory($function);
} else {
if ($childService = $factory->getAttribute('service')) {
$class = new Reference($childService, ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, false);
} else {
$class = $factory->getAttribute('class');
}

$definition->setFactory(array($class, $factory->getAttribute('method')));
}
}

if ($configurators = $this->getChildren($service, 'configurator')) {
$configurator = $configurators[0];
if ($function = $configurator->getAttribute('function')) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,19 @@ private function parseDefinition($id, $service, $file)
$definition->setAbstract($service['abstract']);
}

if (isset($service['factory'])) {
if (is_string($service['factory'])) {
if (strpos($service['factory'], ':')) {
$parts = explode(':', $service['factory']);
$definition->setFactory(array($this->resolveServices('@'.$parts[0]), $parts[1]));
} else {
$definition->setFactory($service['factory']);
}
} else {
$definition->setFactory(array($this->resolveServices($service['factory'][0]), $service['factory'][1]));
}
}

if (isset($service['factory_class'])) {
$definition->setFactoryClass($service['factory_class']);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@
<xsd:attribute name="ignore-errors" type="boolean" />
</xsd:complexType>

<xsd:complexType name="configurator">
<xsd:complexType name="callable">
<xsd:attribute name="id" type="xsd:string" />
<xsd:attribute name="service" type="xsd:string" />
<xsd:attribute name="class" type="xsd:string" />
Expand All @@ -76,7 +76,8 @@
<xsd:choice maxOccurs="unbounded">
<xsd:element name="file" type="xsd:string" minOccurs="0" maxOccurs="1" />
<xsd:element name="argument" type="argument" minOccurs="0" maxOccurs="unbounded" />
<xsd:element name="configurator" type="configurator" minOccurs="0" maxOccurs="1" />
<xsd:element name="configurator" type="callable" minOccurs="0" maxOccurs="1" />
<xsd:element name="factory" type="callable" minOccurs="0" maxOccurs="1" />
<xsd:element name="call" type="call" minOccurs="0" maxOccurs="unbounded" />
<xsd:element name="tag" type="tag" minOccurs="0" maxOccurs="unbounded" />
<xsd:element name="property" type="property" minOccurs="0" maxOccurs="unbounded" />
Expand Down
Loading