Listen to Fabien potencier and talk about symfony2: What is dependency injection?

Source: Internet
Author: User
Tags php session sessionstorage

What is dependency injection?
Analyze dependency injection from the perspective of PHP implementation. Because PHP is mainly used for web development, let's look at the web application example.
To overcome the stateless nature of HTTP, web applications need to store user information between Web requests. The simplest way is to use cookies or use a better PHP built-in session mechanism.

$_SESSION['language']='en';

The above code stores the language in the session variable language. This value can be used for subsequent requests of the same user. Because the $ _ Session array is a global variable. The call method is as follows:

$user_language = $_SESSION['language'];

Because dependency injection is a concept in the object-oriented world, we need to encapsulate the PHP session mechanism into a class and then apply it to Web applications.

class SessionStorage{   function __construct($cookieName = 'PHP_SESS_ID')   {    session_name($cookieName);    session_start();   }      function set($key, $value)   {    $_SESSION[$key] = $value;   }   function get($key)   {    return $_SESSION[$key];   }   //...}

Next, we define a user class to provide its more advanced interfaces.

class User{    protected $storage;        function __construct()    {    $this->$storage = new SessionStorage();    }        function setLanguage($language)    {    $this->storage->set('language', $language);    }    function getLanguage()    {    return $this->storage->get('language');    }       //.....}

Then we can use it directly.

$user = new User();$user->setLanguage('en');$user_language = $user->getLanguage();

What if it is more flexible? What should you do if you want to change the session cookie name? There are several ways: You can specify it in the sessionstorage constructor in the user class, that is, a hard encoding method.

class User{   function __construct()   {      $this->storage = new SessionStorage('SESSION_ID');   }   //....}

It is not recommended to define a constant outside the user class: storage_session_name.

class User{  function __construct()  {    $this->storage = new SessionStorage(STORAGE_SESSION_NAME);  }   // ...}define('STORAGE_SESSION_NAME','SESSION_ID');

One way is to take the session name as a parameter of the user class constructor:

class User{  function __construct($sessionName)  {    $this->storage = new SessionStorage($sessionName);  }   // ...} $user = new User('SESSION_ID');

Another way is to add an optional array of settings options for the session Storage Class in PHP code.

class User{  function __construct($storageOptions)  {    $this->storage = new SessionStorage($storageOptions['session_name']);  }   // ...} $user = new User(array('session_name' => 'SESSION_ID'));

There are many implementation methods. No matter hard encoding, setting it as a constant, being a constructor parameter or an optional array is not the best choice. Although the latter two seem a little better, it makes the user class constructor pile up some parameters that have nothing to do with themselves.

Another problem arises. What if I want to change the sessionstorage class? For example, a false data is generated during a test. Or you want to save the session to the database or memory, you need to change the sessionstorage class. In the current situation, it is impossible to change the sessionstorage class without modifying the user class.

Now we want to consider dependency injection. Instead of creating a sessionstorage object in the user class, we pass the sessionstorage object to the user object as a constructor parameter of the user class after external creation.

class User{  function __construct($storage)  {    $this->storage = $storage;  }   // ...}

OK. This is dependency injection. Nothing else! It may be a little more difficult to use the user class now:

$storage = new SessionStorage('SESSION_ID');$user = new User($storage);

Now, without changing the user class, you can change the session name and sessionstorage class!

To sum up, dependency injection is used by components to obtain their dependent objects through their constructors, methods, or attribute fields.

Constructor injection:

class User{  function __construct($storage)  {    $this->storage = $storage;  }   // ...}

Seter injection (method injection ):

class User{  function setSessionStorage($storage)  {    $this->storage = $storage;  }   // ...}

Property field injection:

class User{  public $sessionStorage;} $user->sessionStorage = $storage;

You will see these figures in symfony:

Constructor injection:

$dispatcher = new sfEventDispatcher();$storage = new sfMySQLSessionStorage(array('database' => 'session', 'db_table' => 'session'));$user = new sfUser($dispatcher, $storage, array('default_culture' => 'en'));

Inject the $ dispatcher object and $ storage object into the $ user object.

Method injection:

$transport = new Zend_Mail_Transport_Smtp('smtp.gmail.com', array(  'auth'     => 'login',  'username' => 'foo',  'password' => 'bar',  'ssl'      => 'ssl',  'port'     => 465,)); $mailer = new Zend_Mail();$mailer->setDefaultTransport($transport);

This injection is commonly known as setter injection.

OK. This is dependency injection. It will develop to service container injection in symfony2. To provide more convenient, flexible, and loosely coupled multi-level dependency management. It is the service container, which provides the most powerful support for the execution efficiency and scalability of symfony2.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.