sfDependencyInjectionContainerPlugin - 1.0.0

sfDependencyInjectionContainerPlugin

You are currently browsing
the website for symfony 1

Visit the Symfony2 website


« Back to the Plugins Home

Signin


Forgot your password?
Create an account

Tools

Stats

advanced search
Information Readme Releases Changelog Contribute
Show source

sfDependencyInjectionContainerPlugin

The sfDependencyInjectionContainerPlugin packages the dependency injection container component into Symfony.

Installation

  • Install the plugin

    $ symfony plugin:install sfDependencyInjectionContainerPlugin
    
  • Clear the cache

    $ symfony cache:clear
    
  • Activate the plugin in the config/ProjectConfiguration.class.php:

    class ProjectConfiguration extends sfProjectConfiguration
    {
      public function setup()
      {
        $this->enablePlugins(array(
          /* ... */
          'sfDependencyInjectionContainerPlugin',
        ));
      }
    }

This plugin must be enabled last to be able to register events and create services through the symfony event dispatcher.

Documentation

Bind your own services

Thanks to the sfEventDispatcher bundled with Symfony, this plugin notify an event after the service container initialization.

To listen to the event, connect to that event name (in your ProjectConfiguration class for example):

$this->dispatcher->connect('service_container.load_configuration', array($this, 'listenToServiceContainerLoadConfiguration'));

Here is an implementation of a listener

public function listenToServiceContainerLoadConfiguration(sfEvent $event)
{
  $container = $event->getSubject();
  $loader    = new sfServiceContainerLoaderFileYaml($container);
  $loader->load(dirname(__FILE__).'/services.yml');
}

Use services in your application

The plugin add two methods to your ProjectConfiguration and your actions, to ease the usage.

  • getServiceContainer()
  • getService()

Example:

public function executeIndex(sfWebRequest $request)
{
  $sc   = $this->getServiceContainer();
  $mail = $sc->mail;
  // or
  $mail = $this->getService('mail');
}

To know more about the dependency injection container component, please refer to the official documentation : (http://components.symfony-project.org/dependency-injection/).