PHPackages                             da/di-bundle - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Framework](/categories/framework)
4. /
5. da/di-bundle

ActiveSymfony-bundle[Framework](/categories/framework)

da/di-bundle
============

Bundle allowing to add parameters to the dependency injection

013PHP

Since Jun 3Pushed 12y ago1 watchersCompare

[ Source](https://github.com/Gnucki/DaDiBundle)[ Packagist](https://packagist.org/packages/da/di-bundle)[ RSS](/packages/da-di-bundle/feed)WikiDiscussions master Synced 2mo ago

READMEChangelogDependenciesVersions (1)Used By (0)

DaDiBundle
==========

[](#dadibundle)

The DaDiBundle is a Symfony2's bundle that allows to use advanced dependency injection features. You can use some new parameters (like `interface` for instance) in the configuration of your services and implement your own.

Installation
------------

[](#installation)

Add the following line to the require section of you composer.json file:

```
"da/di-bundle": "dev-master"
```

Run the composer update command:

```
composer update --dev
```

Add the following line to your AppKernel.php file:

```
new Da\DiBundle\DaDiBundle(),
```

You should now be able to use the DaDiBundle. To benefit of the features of this bundle, you have to use a new `FileLoader` in your dependency injection:

```
// Me/MyBundle/DependencyInjection/MeMyBundleExtension.php

namespace Me\MyBundle\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Da\DiBundle\DependencyInjection\Loader\YamlFileLoader;

class MeMyBundleExtension extends Extension
{
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);

        $loader = YamlFileLoader::decorate($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('services.yml');

        // ...
    }
}
```

Using new parameters
--------------------

[](#using-new-parameters)

This bundle adds some new parameters to help you and demonstrates how you could enhance your experience with the services and the depency injection.

### Interface

[](#interface)

The paramater `interface` allows you to check that a service implements an interface:

```
parameters:
    router.class: Me\MyRoutingBundle\Router

services:
    me-routing.router:
    	interface: Me\MyRoutingBundle\RouterInterface
        class: %router.class%
```

### Factory

[](#factory)

The paramater `factory` allows you to organize your services which have the same responsability:

```
services:
    me-file.parser:
    	interface: Me\FileBundle\Parser\ParserInterface
        factory:
        	yaml:
        		class: Me\FileBundle\Parser\YamlParser
        	xml:
        		class: Me\FileBundle\Parser\XmlParser
        	php:
        		interface: Me\FileBundle\Parser\CodeParserInterface
        		class: Me\FileBundle\Parser\PhpParser
```

You can then access the parser for yaml file service with the id `me-file.parser.yaml` for instance. The service `me-file.parser` is a factory you can use like that in a controller:

```
	$yamlParser = $this->container->get('me-file.parser')->get('yaml');
```

> **Note:**All the parameters of the factory are applied to its manufactored services. In this example, the services `me-file.parser.yaml` and `me-file.parser.xml` have to implement the interface `Me\FileBundle\Parser\ParserInterface` define at the `me-file.parser` level. The service `me-file.parser.php` overrides the `interface` parameter and has to implement the interface `Me\FileBundle\Parser\CodeParserInterface` instead.

### Builder

[](#builder)

The paramater `builder` is just a syntaxic sugar that helps to differentiate the `factory` parameter from the native `factory_class`, `factory_method`, `factory_service`:

```
services:
    me-file.lexer:
    	builder:
    		method: build
    		service: me-file.lexer.builder
    me-file.lexer.builder:
    	class: Me\FileBundle\Lexer\Builder
```

is equivalent to:

```
services:
    me-file.lexer:
    	builder: me-file.lexer.builder # build is the default name of the method.
    me-file.lexer.builder:
    	class: Me\FileBundle\Lexer\Builder
```

is equivalent to:

```
services:
    me-file.lexer:
    	factory_method: build
    	factory_service: me-file.lexer.builder
    me-file.lexer.builder:
    	class: Me\FileBundle\Lexer\Builder
```

Implementing your own parameter
-------------------------------

[](#implementing-your-own-parameter)

This bundle allows you to define your own parameters in a structured way. Let's see the example of the parameter `interface`.

### Create an extra definition

[](#create-an-extra-definition)

```
// Da/DiBundle/DependencyInjection/Definition/InterfaceExtraDefinition.php

namespace Da\DiBundle\DependencyInjection\Definition;

class InterfaceExtraDefinition implements ExtraDefinitionInterface
{
	private $name;

	public function setName($name)
	{
		$this->name = $name;
	}

	public function getName()
	{
		return $this->name;
	}
}
```

This extra definition contains the informations needed for your parameter.

### Add a decorator to the yaml file loader

[](#add-a-decorator-to-the-yaml-file-loader)

```
// Da/DiBundle/DependencyInjection/Loader/InterfaceYamlFileLoaderDecorator.php

namespace Da\DiBundle\DependencyInjection\Loader;

use Symfony\Component\DependencyInjection\Definition;
use Da\DiBundle\DependencyInjection\Definition\InterfaceExtraDefinition;

class InterfaceYamlFileLoaderDecorator extends AbstractYamlFileLoaderDecorator
{
    public function parseExtraDefinition($id, $service, $file, Definition $definition)
    {
        $def = $definition;

    	if (isset($service['interface']))
    	{
            // Parse the extra definition.
            $interfaceExtra = new InterfaceExtraDefinition();
            $interfaceExtra->setName($service['interface']);

            // Add the extra definition to the definition.
            $def = $this->getDecoratedInstance()->getDefinitionExtra($definition);
            $def->setExtra('interface', $interfaceExtra);
        }

        return $this->getParent()->parseExtraDefinition($id, $service, $file, $def);
    }
}
```

This decorator (see the design pattern) takes the parameter `interface` into account and add it as an extra definition in the definition of the service. You have to declare it in your bundle:

```
// Da/DiBundle/DependencyInjection/Compiler/CheckInterfaceValidityPass.php

namespace Da\DiBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Compiler\PassConfig;
use Da\DiBundle\DependencyInjection\Loader\YamlFileLoader;

class DaDiBundle extends Bundle
{
	public function build(ContainerBuilder $container)
    {
        parent::build($container);

		// ...

        YamlFileLoader::addDecorator('Da\DiBundle\DependencyInjection\Loader\InterfaceYamlFileLoaderDecorator');
    }
}
```

### Add a compiler pass

[](#add-a-compiler-pass)

```
// Da/DiBundle/DependencyInjection/Compiler/CheckInterfaceValidityPass.php

namespace Da\DiBundle\DependencyInjection\Compiler;

use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\DefinitionDecorator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
use Symfony\Component\DependencyInjection\Exception\RuntimeException;
use Da\DiBundle\DependencyInjection\Definition\DefinitionExtraInterface;

class CheckInterfaceValidityPass implements CompilerPassInterface
{
    private $container;

    public function process(ContainerBuilder $container)
    {
        $this->container = $container;

        foreach (array_keys($container->getDefinitions()) as $id)
        {
            // yes, we are specifically fetching the definition from the
            // container to ensure we are not operating on stale data
            $definition = $container->getDefinition($id);
            if (!$definition instanceof DefinitionExtraInterface || !$definition->getExtra('interface'))
                continue;

            $this->checkDefinition($id, $definition);
        }
    }

    private function checkDefinition($id, DefinitionExtraInterface $definition)
    {
        $interfaceName = $definition->getExtra('interface')->getName();
        $className = $definition->getClass();

        $class = new \ReflectionClass($className);
        if (!interface_exists($interfaceName))
            throw new InvalidArgumentException('Interface "'.$interfaceName.'" not found.');
        if (!$class->implementsInterface($interfaceName))
        	throw new RuntimeException('The class "'.$className.'" of the service "'.$id.'" should implement the interface "'.$interfaceName.'".');
    }
}
```

This compiler pass checks that your service implements the defined interface. You have to declare it in your bundle:

```
// Da/DiBundle/DaDiBundle.php

namespace Da\DiBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Compiler\PassConfig;
use Da\DiBundle\DependencyInjection\Loader\YamlFileLoader;
use Da\DiBundle\DependencyInjection\Compiler\CheckInterfaceValidityPass;

class DaDiBundle extends Bundle
{
	public function build(ContainerBuilder $container)
    {
        parent::build($container);

		// ...

		YamlFileLoader::addDecorator('Da\DiBundle\DependencyInjection\Loader\InterfaceYamlFileLoaderDecorator');
        $container->addCompilerPass(new CheckInterfaceValidityPass(), PassConfig::TYPE_OPTIMIZE);
    }
}
```

Limitations
-----------

[](#limitations)

All the features have been, for the time being, only developped for yaml configuration file.

Tests
-----

[](#tests)

As the developpement of new parameters can affect others, you can run phpunit on this bundle to check that all the features are still ok after developping your own.

###  Health Score

20

—

LowBetter than 14% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity5

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity41

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

### Community

Maintainers

![](https://www.gravatar.com/avatar/cc6dff73f30c5ee1a374376f984f427f1761d3fbd42bb625e1c3e799bcee6f07?d=identicon)[Gnucki](/maintainers/Gnucki)

---

Top Contributors

[![Gnucki](https://avatars.githubusercontent.com/u/1064697?v=4)](https://github.com/Gnucki "Gnucki (15 commits)")

### Embed Badge

![Health badge](/badges/da-di-bundle/health.svg)

```
[![Health](https://phpackages.com/badges/da-di-bundle/health.svg)](https://phpackages.com/packages/da-di-bundle)
```

###  Alternatives

[laravel/telescope

An elegant debug assistant for the Laravel framework.

5.2k67.8M192](/packages/laravel-telescope)[spiral/roadrunner

RoadRunner: High-performance PHP application server and process manager written in Go and powered with plugins

8.4k12.2M84](/packages/spiral-roadrunner)[nolimits4web/swiper

Most modern mobile touch slider and framework with hardware accelerated transitions

41.8k177.2k1](/packages/nolimits4web-swiper)[laravel/dusk

Laravel Dusk provides simple end-to-end testing and browser automation.

1.9k36.7M259](/packages/laravel-dusk)[laravel/prompts

Add beautiful and user-friendly forms to your command-line applications.

708181.8M596](/packages/laravel-prompts)[cakephp/chronos

A simple API extension for DateTime.

1.4k47.7M121](/packages/cakephp-chronos)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
