Put simply, a Dependency Injection Container alleviates the need for factories and the use of new in your code. Think of DiC as the new new. You will still need to write factories in some cases, but your code will not depend directly on them. Your code will be easier to change, unit test and reuse in other contexts.

This module enables Symfony's Dependency Injection component for Drupal 7 modules.

Requirements

Usage

  1. Add a dependency on this module to your module's .info file:
    dependencies[] = inject
  2. Thick Configuration > Performance > Dump configuration to disk checkbox to cache the dumped version of the container to disk.
  3. Thick Configuration > Performance > Compile configuration checkbox to compile the container before dumping.

The module comes with container dumping activated by default. In a developer environment you may deactivate this functionality to debug the container building process. Deactivating this feature adds a substantial performance hit as more meta-data (Yaml files, config, ...) has to be loaded into memory than might actually be necessary. This may not be relevant to scenarios where caching is in place, however hits hardly in scenarios where no caching is used.

Registering services

The simpler way of registering services for your module is to use a MODULE_NAME.services.yml file located at the root of your module directory.

If you need more control, and/or dynamic parameters to be registered, creates a file called MODULE_NAME.inject.inc and implements hook_inject_build.

You might have a look at the provided test_inject module which implements both examples and gives basic information on how to register your services.

Functional tests has been added in this release, you can see them in the Automated Test tab of project.

For a real example of a module leveraging the dependency overriding mechanism, you might have a look at Doctrine module. The Entity integration module overrides the doctrine.orm.driver to support both Schema API and Annotation Driven entities.

Documentation

And don't forget, public and @Inject are like Elves and Dwarfs: they can work together, but in an ideal world, they would coexist independently.

Project information

Releases