The dependency injection of the aravel framework is indeed very powerful, and dependency injection through containers can selectively load required services to reduce the overhead of the initialization framework. The following is a post I have seen on the Internet, we can share with you that the Laravel framework's dependency injection is indeed very powerful, and the container-based dependency injection can selectively load the required services to reduce the overhead of the initialization framework, below is a post I saw on the Internet, which is well written and shared with you, the article shows the strength of dependency injection from the design of database connections based on traditional classes to the highly decoupled design of container loading service, which is worth learning.
--------------------------------------------------------------- The original article ----------------------------------------------------------
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.
1
_connection = $connection;14 }15 16 public function someDbTask()17 {18 $connection = $this->_connection;19 20 // ...21 }2223 }24 25 $some = new SomeComponent();26 27 //Create the connection28 $connection = new Connection(array(29 "host" => "localhost",30 "username" => "root",31 "password" => "secret",32 "dbname" => "invo"33 ));34 35 //Inject the connection in the component36 $some->setConnection($connection);37 38 $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.
1
"localhost",13 "username" => "root",14 "password" => "secret",15 "dbname" => "invo"16 ));17 }18 19 }20 21 class SomeComponent22 {23 24 protected $_connection;25 26 /**27 * Sets the connection externally28 */29 public function setConnection($connection){30 $this->_connection = $connection;31 }32 33 public function someDbTask()34 {35 $connection = $this->_connection;36 37 // ...38 }39 40 }41 42 $some = new SomeComponent();43 44 //Pass the connection defined in the registry45 $some->setConnection(Registry::getConnection());46 47 $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:
1
"localhost",15 "username" => "root",16 "password" => "secret",17 "dbname" => "invo"18 ));19 }20 21 /**22 * Creates a connection only once and returns it23 */24 public static function getSharedConnection()25 {26 if (self::$_connection===null){27 $connection = self::_createConnection();28 self::$_connection = $connection;29 }30 return self::$_connection;31 }32 33 /**34 * Always returns a new connection35 */36 public static function getNewConnection()37 {38 return self::_createConnection();39 }40 41 }42 43 class SomeComponent44 {45 46 protected $_connection;47 48 /**49 * Sets the connection externally50 */51 public function setConnection($connection){52 $this->_connection = $connection;53 }54 55 /**56 * This method always needs the shared connection57 */58 public function someDbTask()59 {60 $connection = $this->_connection;61 62 // ...63 }6465 /**66 * This method always needs a new connection67 */68 public function someOtherDbTask($connection)69 {70 71 }72 73 }74 75 $some = new SomeComponent();76 77 //This injects the shared connection78 $some->setConnection(Registry::getSharedConnection());79 80 $some->someDbTask();81 82 //Here, we always pass a new connection as parameter83 $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:
1
setConnection($connection);16 $some->setSession($session);17 $some->setFileSystem($fileSystem);18 $some->setFilter($filter);19 $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:
1
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:
1
_di = $di; 11 } 12 13 public function someDbTask() 14 { 15 16 // Get the connection service 17 // Always returns a new connection 18 $connection = $this->_di->get('db'); 19 20 } 21 22 public function someOtherDbTask() 23 { 24 25 // Get a shared connection service, 26 // this will return the same connection everytime 27 $connection = $this->_di->getShared('db'); 28 29 //This method also requires a input filtering service 30 $filter = $this->_db->get('filter'); 31 32 } 33 34 } 35 36 $di = new Phalcon\DI(); 37 38 //Register a "db" service in the container 39 $di->set('db', function(){ 40 return new Connection(array( 41 "host" => "localhost", 42 "username" => "root", 43 "password" => "secret", 44 "dbname" => "invo" 45 )); 46 }); 47 48 //Register a "filter" service in the container 49 $di->set('filter', function(){ 50 return new Filter(); 51 }); 52 53 //Register a "session" service in the container 54 $di->set('session', function(){ 55 return new Session(); 56 }); 57 58 //Pass the service container as unique parameter59 $some = new SomeComponent($di); 60 61 $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 is optimized ¶
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 the service secret in the 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:
1
set("request", 'Phalcon\Http\Request'); 8 9 //Using an anonymous function, the instance will lazy loaded 10 $di->set("request", function(){ 11 return new Phalcon\Http\Request(); 12 }); 13 14 //Registering directly an instance 15 $di->set("request", new Phalcon\Http\Request()); 16 17 //Using an array definition 18 $di->set("request", array( 19 "className" => 'Phalcon\Http\Request' 20 ));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.
1
set("db", array( 5 "className" => "Phalcon\Db\Adapter\Pdo\MySQL", 6 "parameters" => array( 7 "parameter" => array( 8 "host" => "localhost", 9 "username" => "root", 10 "password" => "secret", 11 "dbname" => "blog" 12 ) 13 ) 14 )); 15 16 //Using an anonymous function 17 $di->set("db", function(){ 18 return new Phalcon\Db\Adapter\Pdo\Mysql(array( 19 "host" => "localhost", 20 "username" => "root", 21 "password" => "secret", 22 "dbname" => "blog" 23 )); 24 });The above two service registration methods produce the same results. Then, defined through arrays, you can modify the service parameters as needed:
1
setParameter("db", 0, array(4 "host" => "localhost",5 "username" => "root",6 "password" => "secret"7 ));The simplest way to get a service from a container is to use the get method, which returns a new instance from the container:
1
get("request")Or use the following Magic method:
1
GetRequest (); 4 5 Phalcon \ DI allows service reuse at the same time. to get a service that has been instantiated, you can use the getShared () method;
Specific Phalcon \ Http \ Request example:
1
getShared("request");You can also pass an array parameter to the constructor during the request:
1
get("MyComponent", array("some-parameter", "other"))Understanding PHP dependency injection | LaravelIoC container