Understanding PHP Dependency Injection | Laravel IOC Container ____php

Source: Internet
Author: User

See Laravel's IOC container document is just an introduction to the example, but did not say the principle, before using the MVC framework did not care about this concept, inadvertently in the Phalcon document to see this detailed introduction, feeling suddenly enlightened, copy paste over, mainly for a long time did not write something, now really lazy become.

First, let's assume that we're going to develop a component named Somecomponent. This component will now inject a database connection.

In this example, the database connection is created in component, which is impractical, so we will not be able to change some parameters such as database connection parameters and database types.

<?php

class somecomponent
{

    /**
     * Instantiation of the connection is hardcoded inside
     * The CO Mponent so are difficult to replace it externally
     * or change its behavior
    /Public Function somedbtask ()
    {
        $connection = new Connection (Array (
            "host" => "localhost",
            "username" => "root",
            "password "=>" secret ","
            dbname "=>" Invo "
        ));

        // ...
    }

}

$some = new Somecomponent ();
$some->somedbtask ();

To solve the problem mentioned above, we need to create an external connection and inject it into the container before using it. For now, this looks like a good solution:

<?php

class somecomponent
{

    protected $_connection;

    /**
     * Sets the connection externally
    /Public Function setconnection ($connection)
    {
        $this->_ connection = $connection;
    }

    Public Function Somedbtask ()
    {
        $connection = $this->_connection;

        // ...
    }

}

$some = new Somecomponent ();

Create the connection
$connection = new Connection (Array (
    "host" => "localhost",
    "username" => " Root ","
    password "=>" secret ",
    " dbname "=>" Invo "
));

Inject the connection in the component
$some->setconnection ($connection);

$some->somedbtask ();

Now let's consider a problem where we use this component in different parts of the application to create a database connection multiple times. Use a method similar to the global Registry, from which you can get a database connection instance, instead of using it once.

<?php

class Registry
{

    /**
     * Returns the connection * * Public
    static function Getconnection ()
    {return
       new Connection (Array (
            "host" => "localhost",
            "username" => "root",
            "Password" => "secret",
            "dbname" => "Invo"
        ));
    }

Class Somecomponent
{

    protected $_connection;

    /**
     * Sets the connection externally
    /Public Function setconnection ($connection) {
        $this->_ connection = $connection;
    }

    Public Function Somedbtask ()
    {
        $connection = $this->_connection;

        // ...
    }

}

$some = new Somecomponent ();

Pass the connection defined in the registry
$some->setconnection (Registry::getconnection ());

$some->somedbtask ();

Now, let's imagine that we have to implement two methods in the component, first we need to create a new database connection, and the second one always gets a shared connection:

<?php class Registry {protected static $_connection; /** * Creates a connection/protected static function _createconnection () {return new Connect Ion (Array ("host" => "localhost", "username" => "root", "password" => "secret"
    "," dbname "=>" Invo "));
    }/** * Creates a connection only once and returns it/public static function Getsharedconnection ()
            {if (self::$_connection===null) {$connection = Self::_createconnection ();
        Self::$_connection = $connection;
    return self::$_connection; }/** * Always returns a new connection */public static function GetNewConnection () {Retu
    RN Self::_createconnection ();

    } class Somecomponent {protected $_connection;
    /** * Sets The connection externally/Public function setconnection ($connection) {    $this->_connection = $connection; /** * This method always needs the shared connection/public function Somedbtask () {$c

        onnection = $this->_connection;

    // ...
    } 

/** * This method always needs a new connection */Public Function Someotherdbtask ($connection) {}

} $some = new Somecomponent ();

This injects the shared connection $some->setconnection (Registry::getsharedconnection ());

$some->somedbtask (); Here we are always pass a new connection as parameter $some->someotherdbtask (Registry::getconnection ());

So far, we've seen how to use dependency injection to solve our problems. Rather than creating a dependency within the code, rather than having it passed as a parameter, it makes our program easier to maintain, reduce the coupling of program code, and achieve a loose coupling. But in the long run, this form of dependency injection has some drawbacks.

For example, if there are more dependencies in the component, we need to create multiple setter method passes, or create constructors for delivery. In addition, each time you use a component, you need to create a dependency component that makes code maintenance difficult, and the code we write might look like this:

<?php

//create the dependencies or retrieve them from the registry
$connection = new Connection ();
$session = new session ();
$fileSystem = new filesystem ();
$filter = new Filter ();
$selector = new selector ();

Pass them as constructor parameters
$some = new Somecomponent ($connection, $session, $fileSystem, $filter, $selecto R);

.. or using Setters

$some->setconnection ($connection);
$some->setsession ($session);
$some->setfilesystem ($fileSystem);
$some->setfilter ($filter);
$some->setselector ($selector);

I think we have to create this object in many parts of the application. If you don't need to rely on components, we have to go to the Code injection section to remove the parameters in the constructor or the setter method. To solve this problem, we return to use a global registry to create the component. However, before you create an object, it adds a new layer of abstraction:

<?php

class somecomponent
{

    //...

    /**
     * Define A factory method to create Somecomponent instances injecting its dependencies/public
    static FU Nction Factory ()
    {

        $connection = new Connection ();
        $session = new session ();
        $fileSystem = new filesystem ();
        $filter = new Filter ();
        $selector = new selector ();

        return new self ($connection, $session, $fileSystem, $filter, $selector);
    }


At this moment, we seem to be back to the beginning of the problem, we are creating dependencies within the component, we are revising and looking for a solution to the problem every time, but that's not a good idea.

A practical and elegant solution to these problems, is to use the container's dependency injection, as we saw earlier, the container as a global registry, using the container's dependency injection as a bridge to resolve dependencies can make our code less coupled, and well reduce the complexity of the components:

<?php class Somecomponent {protected $_di;
    Public function __construct ($di) {$this->_di = $di; The Public Function Somedbtask () {//Get the Connection service//Always returns a new Connectio

    n $connection = $this->_di->get (' db '); The Public Function Someotherdbtask () {//Get a Shared connection service,//This'll return th

        E same connection Everytime $connection = $this->_di->getshared (' db ');

    This method also requires a input filtering service $filter = $this->_db->get (' filter ');

}} $di = new Phalcon\di (); Register a "DB" service in the container $di->set (' db ', function () {return new Connection (Array ("host" = > "localhost", "username" => "root", "password" => "secret", "dbname" => "Invo")
;

});
 Register a "filter" service in the container $di->set (' Filter ', function () {   return new Filter ();

});

Register a "session" service in the container $di->set (' Sessions ', function () {return to new session ();});

Pass the service container as unique parameter $some = new Somecomponent ($DI); $some->sometask ();

Now, the component needs it only when it accesses a service, and if it doesn't, it doesn't even initialize it to save resources. The component is highly decoupled. Their behavior, or any other aspect of them, will not affect the component itself.
Our approach to implementation

Phalcon\di is a component that implements the dependency injection function of a service and is itself a container.

Because Phalcon is highly decoupled, Phalcon\di is an essential part of the framework for integrating other components, and developers can use this component to rely on injecting and managing instances of files that are not identical in the application.

Basically, this component implements the inversion of control mode. Based on this, the object no longer receives parameters by constructor or uses setter to implement injection, but rather directly requests dependency injection of the service. This greatly reduces the complexity of the overall program because there is only one way to get the dependencies of one component that is needed.

In addition, this pattern enhances the testability of the code, making it less prone to error.
Registering a service in a container ¶

The framework itself or developers can register the service. When a component a requires a call to component B (or an instance of its class), you can request the invocation of component B in a leisurely setting, rather than creating an instance of component B.

This way of working provides us with a number of advantages:

We can replace a component that is easy to create from themselves or from a third party.
Before the component is released, we can fully control the initialization of the object and make various settings for the object.
We can use a unified approach to get a structured global instance from the component

A service can be injected into a container in several ways:

<?php

//create the Dependency Injector Container
$di = new Phalcon\di ();

By its class name
$di->set ("Request", ' phalcon\http\request ');

Using an anonymous function, the instance would lazy loaded
$di->set ("Request", function () {return
    new Phalco N\http\request ();
});

Registering directly an instance
$di->set ("Request", new Phalcon\http\request ());

Using an array definition
$di->set ("Request", Array (
    "ClassName" => ' Phalcon\http\request '
)) ;

In the example above, when a request is accessed to a framework request, it first determines whether the service for this "reqeust" name exists in the container.

The container returns an instance of the request data, and the developer eventually gets the component they want.

Each of the methods in the previous example has advantages and disadvantages, depending on which particular scenario is used in the development process.

Using a string to set a service is simple, but lacks flexibility. When you set up a service, using arrays provides more flexibility, and you can use more complex code. Lambda functions are a good balance between the two, but they can also lead to more maintenance management costs.

PHALCON\DI provides a delayed load of services. Unless the developer instantiates an object directly while injecting the service, it is stored in the container. In a container, a service that is stored through arrays, strings, and so on, is deferred loading, that is, it is initialized only when the object is requested.

<?php

//register a service "DB" with a class name and its parameters
$di->set ("DB", Array (
    "className" = > "Phalcon\db\adapter\pdo\mysql",
    "parameters" => Array (
          "parameter" => Array (
               "host" => LocalHost ","
               username "=>" root ",
               " password "=>" secret ",
               " dbname "=>" blog "
          )
));

The Using a anonymous function
$di->set ("db", function () {return
    new Phalcon\db\adapter\pdo\mysql Array ( "
         host" => "localhost", "
         username" => "root",
         "password" => "secret",
         "dbname" => " Blog ")
    );

The registration of these two services produces the same result. Then, through the array definition, you can modify the service parameters when needed later:

<?php

$di->setparameter ("db", 0, Array (
    "host" => "localhost",
    "username" => "root",
    "Password" => "secret")
);

The easiest way to get a service from a container is to use the "get" method, which returns a new instance from the container:

<?php 
$request = $di->get ("request");

Or it can be invoked in the form of the following magic method:

<?php

$request = $di->getrequest ();

Phalcon\di also allows services to be reused, in order to get a service that has already been instantiated, you can use the form of the getshared () method to get the service.

Examples of specific phalcon\http\request requests:

<?php

$request = $di->getshared ("request");

Parameter can also be passed by passing an array parameter to the constructor at the time of the request:

<?php

$component = $di->get ("MyComponent", Array ("Some-parameter", "other"))

Original link: http://www.yuansir-web.com/?p=1012&preview=true

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.