This article mainly introduces the understanding of PHP dependency injection, and analyzes in detail the related concepts and principles of PHP dependency injection based on the instance form, for more information about PHP dependency injection, see the examples in this article. We will share this with you for your reference. The details are as follows:
Reading Laravel's IoC container documentation only introduces instances, but does not describe the principles. I didn't care about this concept before using the MVC framework. I accidentally saw this detailed introduction in the phalcon documentation, and I felt very open, copy and paste it, mainly because I haven't written anything for a long time. now it's really lazy!
First, let's assume that we want to develop a component named SomeComponent. A database connection will be injected into this component.
In this example, the database connection is created in component. this method is impractical. in this case, we cannot change the database connection parameters, database types, and other parameters.
class SomeComponent { /** * The instantiation of the connection is hardcoded inside * the component so is 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 before use and inject it into the container. For the moment, this seems to be a good solution:
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. We use this component in different places in the application, and will create database connections multiple times. Use a method similar to the global registry to obtain a database connection instance, instead of creating it once.
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 must implement two methods in the component. First, we need to create a new database connection, and the second always gets a shared connection:
class Registry{ protected static $_connection; /** * Creates a connection */ protected static function _createConnection() { return new Connection(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() { return 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() { $connection = $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 always pass a new connection as parameter$some->someOtherDbTask(Registry::getConnection());
So far, we have seen how to use dependency injection to solve our problems. Instead of creating dependencies inside the code, it is passed as a parameter, which makes our program easier to maintain, reduces the coupling degree of the program code, and implements a loose coupling. However, in the long run, this form of dependency injection also has some disadvantages.
For example, if the component has many dependencies, we need to create multiple setter methods for passing, or create constructors for passing. In addition, every time you use a component, you need to create a dependency component to make code maintenance less convenient. the code we write may look like this:
//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, $selector);// ... 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 places of the application. If you do not need the dependent components, we need to go to the code injection section to remove the parameters or setter methods in the constructor. To solve this problem, we return to use a global registry to create a component. However, before creating an object, it adds a new abstraction layer:
class SomeComponent{ // ... /** * Define a factory method to create SomeComponent instances injecting its dependencies */ public static function 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 have returned to the beginning of the problem. we are creating dependencies within the component. every time we modify and find a solution to the problem, this is not a good practice.
A practical and elegant solution to these problems is to use container dependency injection. as we can see earlier, containers serve as the global registry, using container dependency injection as a bridge to solve dependencies can lower the coupling degree of our code and greatly reduce the complexity of components:
class SomeComponent{ protected $_di; public function __construct($di) { $this->_di = $di; } public function someDbTask() { // Get the connection service // Always returns a new connection $connection = $this->_di->get('db'); } public function someOtherDbTask() { // Get a shared connection service, // this will return the 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('session', function(){ return new Session();});//Pass the service container as unique parameter$some = new SomeComponent($di);$some->someTask();
Currently, this component only needs to access a service. if it does not, it does not even need to be initialized to save resources. This component is highly decoupled. Their behavior, or any other aspect of them, does not affect the component itself. Our implementation method
Phalcon \ DI is a component that implements the service dependency injection function. it is also a container.
Because Phalcon is highly decoupled, Phalcon \ DI is an essential part of the framework used to integrate other components, developers can also use this component to inject and manage instances of different types of files in an application.
Basically, this component implements the Inversion of Control mode. Based on this, the object does not receive parameters by constructor or inject in setter mode, but directly requests service dependency injection. This greatly reduces the complexity of the entire program, because only one method is used to obtain the dependencies of a required component.
In addition, this mode enhances code testability so that it is not prone to errors.
Register a service in a container
The framework itself or developers can register the service. When A component A requires calling component B (or an instance of its class), it can request calling component B from the container instead of creating an instance of component B.
This method provides us with many advantages:
We can replace a component and create it easily from itself or a third party.
Before the component is released, we can fully control the initialization of the object and perform various settings on the object.
We can get a structured global instance from the component in a unified way.
Services can be injected to containers in the following ways:
//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 will lazy loaded$di->set("request", function(){ return new Phalcon\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 preceding example, when a request is sent to the framework to access data, it first determines whether the service named "reqeust" exists in the container.
The container returns an instance that requests data, and developers finally get the component they want.
Each method in the preceding example has advantages and disadvantages. which method is used depends on the specific scenario in the development process.
Setting a service with a string is very simple, but lacks flexibility. When setting services, array provides more flexibility and can use more complex code. Lambda functions are a good balance between the two, but they may also lead to more maintenance and management costs.
Phalcon \ DI provides delayed loading of services. Unless a developer instantiates an object during service injection and stores it in a container. In containers, services stored in arrays, strings, and other methods will be loaded with delay, that is, they will be initialized only when the request object is called.
//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" ) )));//Using an anonymous function$di->set("db", function(){ return new Phalcon\Db\Adapter\Pdo\Mysql(array( "host" => "localhost", "username" => "root", "password" => "secret", "dbname" => "blog" ));});
The above two service registration methods produce the same results. Then, defined through arrays, you can modify the service parameters as needed:
$di->setParameter("db", 0, array( "host" => "localhost", "username" => "root", "password" => "secret"));
The simplest way to get a service from a container is to use the get method, which returns a new instance from the container:
$request = $di->get("request");
Or use the following Magic method:
$request = $di->getRequest();
Phalcon \ DI allows service reuse at the same time. to obtain an instantiated service, you can use the getShared () method to obtain the service.
Specific Phalcon \ Http \ Request example:
$request = $di->getShared("request");
You can also pass an array parameter to the constructor during the request:
$component = $di->get("MyComponent", array("some-parameter", "other"));
I hope this article will help you with PHP programming.
For more information about PHP dependency injection, see The PHP Chinese web!