PHPackages                             runopencode/traitor-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. [Utility &amp; Helpers](/categories/utility)
4. /
5. runopencode/traitor-bundle

ActiveSymfony-bundle[Utility &amp; Helpers](/categories/utility)

runopencode/traitor-bundle
==========================

Inject into services via method injection based on used traits of defined service classes.

2.0.0(9y ago)461MITPHPPHP &gt;=7.0

Since May 27Pushed 9y ago3 watchersCompare

[ Source](https://github.com/RunOpenCode/traitor-bundle)[ Packagist](https://packagist.org/packages/runopencode/traitor-bundle)[ RSS](/packages/runopencode-traitor-bundle/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependencies (13)Versions (11)Used By (0)

Traitor bundle
==============

[](#traitor-bundle)

[![Packagist](https://camo.githubusercontent.com/fbec7c7100f61f899ac935384c387bbd44c7ef06c86dc7c7d89c624e57e04b3b/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f52756e4f70656e436f64652f74726169746f722d62756e646c652e737667)](https://packagist.org/packages/runopencode/traitor-bundle)[![Scrutinizer Code Quality](https://camo.githubusercontent.com/159ae0255d3d656756092c905eb1c1bfb3a4052d1b19603dd631fb3b0cf2b4ff/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f52756e4f70656e436f64652f74726169746f722d62756e646c652f6261646765732f7175616c6974792d73636f72652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/RunOpenCode/traitor-bundle/?branch=master)[![Build Status](https://camo.githubusercontent.com/9fd65618187ea61fe163ce1b414574b03ed0622bb37cca2d251eab821edcecc4/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f52756e4f70656e436f64652f74726169746f722d62756e646c652f6261646765732f6275696c642e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/RunOpenCode/traitor-bundle/build-status/master)[![Code Coverage](https://camo.githubusercontent.com/40c4e7d8cfd69ec3ad012d686e0dc4426a1794a18791deb6a0701aba3bd26ba3/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f52756e4f70656e436f64652f74726169746f722d62756e646c652f6261646765732f636f7665726167652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/RunOpenCode/traitor-bundle/?branch=master)[![Build Status](https://camo.githubusercontent.com/a86867071c8da15d9e8747f77d58f3fb2c5d40b41fdd3b9e21249cd7b2743ebc/68747470733a2f2f7472617669732d63692e6f72672f52756e4f70656e436f64652f74726169746f722d62756e646c652e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/RunOpenCode/traitor-bundle)

[![SensioLabsInsight](https://camo.githubusercontent.com/6d8fafa304bff1dddfde9148b1599651b43c04c97a1b5fea8b2a76f1d223cd86/68747470733a2f2f696e73696768742e73656e73696f6c6162732e636f6d2f70726f6a656374732f33613466383161372d363232372d343063352d383966352d3633383230336439653765362f6269672e706e67)](https://insight.sensiolabs.com/projects/3a4f81a7-6227-40c5-89f5-638203d9e7e6)

\*Symfony service container compiler pass which defines additional setter injection of services/parameters/values based on used traits in service classes.

**Before you start using this bundle** please read following article (if you have not already): [http://symfony.com/doc/current/components/dependency\_injection/types.html](http://symfony.com/doc/current/components/dependency_injection/types.html), it is imperative that you fully understand types of injection because this bundle promotes setter injection (which is considered as non-preferred method when comparing to constructor injection) in order to get higher level of productivity.

**We would like you to read carefully this "readme" file as well and understand what this bundle does, with all its benefits and drawbacks, before using it, especially if you are not experienced developer with proficiency in computer science.**

How this bundle works?
----------------------

[](#how-this-bundle-works)

**In one sentence**: If your class is registered as service in service container and if that class uses traits like, per example, `\Psr\Log\LoggerAwareTrait`, this bundle will redefine your service adding a method call in its definition, injecting appropriate service, as per example, a `logger`.

So, instead of defining setter injection for your service, it is sufficient enough to use some kind of provided, or user defined, `*AwareTrait` and this bundle will provide appropriate injection (if it is configured properly, of course).

### Why would you consider such method of defining setter injection?

[](#why-would-you-consider-such-method-of-defining-setter-injection)

Consider that you already have defined services in your service container which requires additional injection of, per example, services that will be used in your code.

Per example:

```
class MyService
{
    public function __construct() {  }
}

```

And your `services.yml`:

```
services:
    my_service
        class: MyService

```

In order to inject, per example, a `logger` service into your service, you would have to modify your class, with, per example, a constructor injection:

```
class MyService
{
    protected $logger

    public function __construct(\Psr\Log\LoggerInterface $logger)
    {
        $this->logger = $logger;
    }
}

```

And you would have to modify `services.yml` as well:

```
services:
    my_service
        class: MyService
        argumets: [ '@logger' ]

```

In example above, a good practice of service injection is exercised. However, sometimes, this good practice can not be satisfied within a reasonable amount of time and effort.

#### Traitor bundle in the rescue

[](#traitor-bundle-in-the-rescue)

Instead of doing as in example stated above, how about to just use some trait, and some kind of *"magic"* will to the rest of it? Our previous example would be as easy as doing the following:

```
class MyService
{
    use \Psr\Log\LoggerAwareTrait;

    public function __construct() {  }
}

```

And this is just good enough - you just use appropriate trait, and compiler pass within this bundle will provide your service class with appropriate setter injection.

#### Motivation for developing this bundle

[](#motivation-for-developing-this-bundle)

Best example, which was a motivation to build this kind of bundle, is GeneratorBundle: .

Namely, GeneratorBundle generates all CRUD bits for you, which includes a form types as well, which are (as per courtesy of authors of this awesome library) already properly registered in service container with tag `form.type`, and, as good as it is, sometimes can be an issue to inject additional required services, which happens quite often.

In order to do such injection, you would have to identify the name of service under which your form type has been registered, and modify that service by either overriding its definition via configuration file in, per example, `app/config/services.yml` (thanks to configuration cascade) or through compiler pass.

However, we have figure out that either of that approaches just takes too much time when we worked on project in which there were app. 50 form types in need of injection of additional services.

So, we needed a solution that will handle this more elegantly, with less effort.

There are other similar solutions out there as well, like [JMSDiExtraBundle](http://jmsyst.com/bundles/JMSDiExtraBundle)which allows you to achieve the same via annotations.

Why this bundle should be used carefully?
-----------------------------------------

[](#why-this-bundle-should-be-used-carefully)

- Setter injection should be used for optional injections only. However, this solution proposes injection of required services as well via setter injection. That is not as bad as, per example, Laravel's Facade, but if it is used without understanding types of injection, it can be dangerous, mostly for developer who develops such practice without understanding the difference.
- Symfony proposes certain convention of defining services for sake of the productivity and maintainability of the project. This bundle breaks that convention, and if developers are not familiar with usage of this bundle, they could have difficulty to understand how certain services got their required dependencies.
- Compiler pass at first run can have impact on performances, considering that this bundle analyses all services and all traits used by their classes, as well as inheritance map of classes, as well as related usage of traits. However, trough configuration, you can narrow down a scope of search and increase performances of compiler pass.

Having in mind all dangers stated above, this bundle can help you a lot in certain use cases, giving you a flexibility and productivity at the cost of good coding practice, and you should use this bundle in such occurrences.

Please note that this bundle **should not be used for redistributable Symfony bundles**, for obvious reasons.

Configuration
-------------

[](#configuration)

Require this bundle via composer, `composer require runopencode/traitor-bundle`and register it in your `AppKernel.php`:

```
class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = [

            ...

            new RunOpenCode\Bundle\Traitor\TraitorBundle()

            ...

        ];
        return $bundles;
    }

}

```

and configure it, example of full configuration is given bellow:

```
runopencode_traitor:
    use_common_traits: false
    inject:
        'Full\Qualified\Trait\Namespace':
            - [ 'setterMethodName', [ '@service_name', 'or_parameter_value' ]]
            - { method: 'otherSetterMethodName', arguments: [ '@service_name', 'or_parameter_value' ] }
    filters:
        tags: [ 'form.type', 'other_tag' ]
        namespaces: [ '\Namespace\Prefix1', 'Namespace\Prefix2' ]
    exclude:
        tags: [ 'tag.to.exclude' ]
        services: [ 'my.service.to_exclude' ]
        classes: [ '\Exclude\Services\ThatUsesThisClass', '\Or\Uses\ThisClass' ]
        namespaces: [ '\Exclude\AllServices\WithClasses\WithinThisNamespace\' ]

```

- `use_common_traits`: Optional. This bundle provides you with common traits within `\RunOpenCode\Bundle\Traitor\Traits` namespace to boost up your productivity. If you are using them, set this parameter to `true`, it will add those traits to injection map. Full list of traits which you can use *out-of-the-box* are given bellow.
- `inject`: Optional. Associative array of traits which should be checked for usage, and if they are used in service class, trait map defines setter injection in same way as Symfony `calls` definition does, an array, with first parameter that defines a method to call, and second parameter as array of arguments to pass to that method call, or, you can use associative array with keys `method`and `atributes`.
- `filters`: Optional. In order not to scan all service classes, you can narrow down the subset to certain namespaces and/or service tags. Determining which class uses which trait can be expensive, this bundle checks both inheritance as well as related traits usage (e.g. if trait uses trait).
- `exclude`: Optional. You can exclude certain services, tagged services, service classes and namespaces to be even considered for this kind of injection.

### XML configuration

[](#xml-configuration)

You can, of course, configure bundle via XML configuration (preferred way), and in doing so, there is [XML Schema](src/RunOpenCode/Bundle/Traitor/Resources/config/schema/configuration-1.0.0.xsd) file available to you for validation and intelli sense for your configration.

### Provided common traits

[](#provided-common-traits)

As previously mentioned, this bundle provides you with common traits which you may or may not use, however, if you are using them, make sure that in your configuration set `use_common_traits` to true, and `inject`map will be appended with following definitions as well:

```
'Symfony\Component\DependencyInjection\ContainerAwareTrait': ['setContainer', ['@service_container']]
'Psr\Log\LoggerAwareTrait': ['setLogger', ['@logger']]
'RunOpenCode\Bundle\Traitor\Traits\DoctrineAwareTrait': ['setDoctrine', ['@doctrine']]
'RunOpenCode\Bundle\Traitor\Traits\EventDispatcherAwareTrait': ['setEventDispatcher', ['@event_dispatcher']]
'RunOpenCode\Bundle\Traitor\Traits\FilesystemAwareTrait': ['setFilesystem', ['@filesystem']]
'RunOpenCode\Bundle\Traitor\Traits\KernelAwareTrait': ['setKernel', ['@kernel']]
'RunOpenCode\Bundle\Traitor\Traits\MailerAwareInterface': ['setMailer', ['@mailer']]
'RunOpenCode\Bundle\Traitor\Traits\PropertyAccessorAwareTrait': ['setPropertyAccessor', ['@property_accessor']]
'RunOpenCode\Bundle\Traitor\Traits\RequestStackAwareTrait': ['setRequestStack', ['@request_stack']]
'RunOpenCode\Bundle\Traitor\Traits\RouterAwareTrait': ['setRouter', ['@router']]
'RunOpenCode\Bundle\Traitor\Traits\AuthorizationCheckerAwareTrait': ['setAuthorizationChecker', ['@security.authorization_checker']]
'RunOpenCode\Bundle\Traitor\Traits\SessionAwareTrait': ['setSession', ['@session']]
'RunOpenCode\Bundle\Traitor\Traits\TwigAwareTrait': ['setTwig', ['@twig']]
'RunOpenCode\Bundle\Traitor\Traits\TranslatorAwareTrait': ['setTranslator', ['@translator']]
'RunOpenCode\Bundle\Traitor\Traits\ValidatorAwareTrait': ['setValidator', ['@validator']]
'RunOpenCode\Bundle\Traitor\Traits\TokenStorageAwareTrait': ['setTokenStorage', ['@security.token_storage']]

```

In general, common traits will help you to boost your productivity when injecting following services:

- `service_container`
- `logger`
- `doctrine`
- `event_dispatcher`
- `filesystem`
- `kernel`
- `mailer`
- `property_accessor`
- `request_stack`
- `router`
- `security.authorization_checker`
- `session`
- `twig`
- `translator`
- `validator`
- `security.token_storage`

###  Health Score

30

—

LowBetter than 65% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity14

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity64

Established project with proven stability

 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.

###  Release Activity

Cadence

Every ~37 days

Recently: every ~81 days

Total

10

Last Release

3300d ago

Major Versions

0.5.1 → 1.0.02016-05-29

1.1.3 → 2.0.02017-04-26

PHP version history (2 changes)0.5.0PHP &gt;=5.5

2.0.0PHP &gt;=7.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/07cd3f36afbf3a9027999c21855055eaf0693fbfce628ee49e81d506fa74b35f?d=identicon)[TheCelavi](/maintainers/TheCelavi)

---

Top Contributors

[![TheCelavi](https://avatars.githubusercontent.com/u/410738?v=4)](https://github.com/TheCelavi "TheCelavi (31 commits)")

---

Tags

dependency-injectionsetter injectionmethod injectiontraits based injectionaware injection

###  Code Quality

TestsPHPUnit

Code StylePHP\_CodeSniffer

### Embed Badge

![Health badge](/badges/runopencode-traitor-bundle/health.svg)

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

###  Alternatives

[php-di/invoker

Generic and extensible callable invoker

26857.8M56](/packages/php-di-invoker)[level-2/dice

A minimalist Dependency injection container (DIC) for PHP. Please note: 3.0+ is only compatible with PHP 7.0. The 2.0 branch is compatbile with PHP 5.6.

437730.3k17](/packages/level-2-dice)[respect/config

A powerful, small, deadly simple configurator and dependency injection container made to be easy.

10211.4k1](/packages/respect-config)[arokettu/phpstorm-metadata-export

Export PhpStorm Advanced Metadata from DI containers

1234.0k1](/packages/arokettu-phpstorm-metadata-export)[x-wp/di

The dependency injection container for WordPress

301.1k10](/packages/x-wp-di)[michaels/data-manager

Simple data manager for nested data, dot notation array access, extendability, and container interoperability.

121.9k2](/packages/michaels-data-manager)

PHPackages © 2026

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