feature #20648 [DependencyInjection] Added a shortcut method for autowired definitions (wouterj)
This PR was merged into the 3.3-dev branch.
Discussion
----------
[DependencyInjection] Added a shortcut method for autowired definitions
| Q | A
| ------------- | ---
| Branch? | master
| Bug fix? | no
| New feature? | yes
| BC breaks? | no
| Deprecations? | no
| Tests pass? | yes
| Fixed tickets | -
| License | MIT
| Doc PR | todo
This is a simple proposal to make adding autowired definitions to the `ContainerBuilder` a little easier. Registering autowired services in PHP code was quite verbose at the moment, while the whole point of autowiring is quick service registration.
**Before**
```php
$container->register('app.twig_extension', AppExtension::class)
->setAutowired(true)
->addTag('twig.extension')
;
```
**After**
```php
$container->autowire('app.twig_extension', AppExtension::class)
->addTag('twig.extension')
;
```
With https://github.com/symfony/symfony/pull/20264, this will be even nicer:
```php
$container->autowire(AppExtension::class)
->addTag('twig.extension')
;
```
Commits
-------
6ef4ce8
Added a shortcut method for autowired definitions
This commit is contained in:
commit
22586ca996
@ -710,6 +710,22 @@ class ContainerBuilder extends Container implements TaggedContainerInterface
|
||||
return $this->setDefinition($id, new Definition($class));
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers an autowired service definition.
|
||||
*
|
||||
* This method implements a shortcut for using setDefinition() with
|
||||
* an autowired definition.
|
||||
*
|
||||
* @param string $id The service identifier
|
||||
* @param null|string $class The service class
|
||||
*
|
||||
* @return Definition The created definition
|
||||
*/
|
||||
public function autowire($id, $class = null)
|
||||
{
|
||||
return $this->setDefinition($id, (new Definition($class))->setAutowired(true));
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds the service definitions.
|
||||
*
|
||||
|
@ -82,6 +82,15 @@ class ContainerBuilderTest extends \PHPUnit_Framework_TestCase
|
||||
$this->assertInstanceOf('Symfony\Component\DependencyInjection\Definition', $builder->getDefinition('foo'), '->register() returns the newly created Definition instance');
|
||||
}
|
||||
|
||||
public function testAutowire()
|
||||
{
|
||||
$builder = new ContainerBuilder();
|
||||
$builder->autowire('foo', 'Bar\FooClass');
|
||||
|
||||
$this->assertTrue($builder->hasDefinition('foo'), '->autowire() registers a new service definition');
|
||||
$this->assertTrue($builder->getDefinition('foo')->isAutowired(), '->autowire() creates autowired definitions');
|
||||
}
|
||||
|
||||
public function testHas()
|
||||
{
|
||||
$builder = new ContainerBuilder();
|
||||
|
Reference in New Issue
Block a user