search
HomeBackend DevelopmentPHP TutorialDependency injection and inversion of control in php, php injection inversion_PHP tutorial

php dependency injection and inversion of control, php injection inversion


DI——Dependency Injection Dependency Injection

IoC——Inversion of Control

To understand the above two concepts, you must understand the following questions:

1. Who are the participants? ​

Answer: Generally there are three parties, one is an object; one is the IoC/DI container; and the other is an external resource of an object. Let me explain the nouns again. An object refers to any ordinary Java object; the IoC/DI container simply refers to a framework program used to implement IoC/DI functions; the external resources of the object refer to the object. Needed, but obtained from outside the object, are collectively referred to as resources, such as: other objects needed by the object, or file resources needed by the object, etc.

2. Dependence: Who depends on whom? Why are there dependencies?

Answer: An object depends on the IoC/DI container. Dependencies are inevitable. In a project, there are various relationships between various classes, and it is impossible for them all to be completely independent, which forms dependencies. Traditional development uses direct calls when using other classes, which will form strong coupling, which should be avoided. Dependency injection borrows containers to transfer dependent objects to achieve decoupling.

3. Injection: Who injects into whom? What exactly is injected?

Answer: Inject the external resources needed into the object through the container

4. Inversion of control: Who controls whom? Control what? Why is it called reversal?

Answer: The container control object of IoC/DI mainly controls the creation of object instances. Reversal is relative to positive direction, so what counts as positive direction? Think about the application under normal circumstances. If you want to use C inside A, what would you do? Of course, the object of C is created directly, that is, the required external resource C is actively obtained in class A. This situation is called forward. So what is reverse? That is, class A no longer actively obtains C, but passively waits for the IoC/DI container to obtain an instance of C, and then injects it into class A in reverse.

5. Are dependency injection and inversion of control the same concept?

Answer: As can be seen from the above: Dependency injection is described from the perspective of the application. Dependency injection can be described completely: the application relies on the container to create and inject the external resources it needs; and inversion of control is from the perspective of the application. The description is from the perspective of the container. The complete description is: the container controls the application, and the container reversely injects the external resources required by the application into the application.

Let’s take a look at some implementation methods of dependency injection through examples:

 1.Constructor injection

<?<span>php
</span><span>class</span><span> Book {
   </span><span>private</span> <span>$db_conn</span><span>;
 
   </span><span>public</span> <span>function</span> __construct(<span>$db_conn</span><span>) {
       </span><span>$this</span>->db_conn = <span>$db_conn</span><span>;
   }
}</span>

2. Setter injection

<?<span>php<br />
  <br />class book{<br />     private $db;<br />   private $file;<br />     function setdb($db){<br />          $this->db=$db;<br />     }<br />     function setfile($file){<br />         $this->file=$file;<br />     }<br />}<br />class file{}<br />class db{}<br />...<br /><br />class test{<br /></span><span>    $book</span> = <span>new</span><span> Book();
    </span><span>$book</span>->setdb(<span>new db()</span><span>);  <br /></span><span>      $book->setfile(new file());<br />}
</span>?>

 

The code of the above two methods is very clear, but when we need to inject many dependencies, it means adding a lot of lines, which will be more difficult to manage.

A better solution is to create a class as the container for all dependencies. In this class, you can store, create, obtain, and find the required dependencies

<?<span>php
</span><span>class</span><span> Ioc {
   </span><span>protected</span> <span>$db_conn</span><span>;
   </span><span>public</span> <span>static</span> <span>function</span><span> make_book() {
       </span><span>$new_book</span> = <span>new</span><span> Book();
       </span><span>$new_book</span>->set_db(self::<span>$db_conn</span><span>);
       </span><span>//</span><span>...
       //...
       //其他的依赖注入</span>
       <span>return</span> <span>$new_book</span><span>;
   }
}</span>

At this time, if you want to obtain a book instance, you only need to execute $newone = Ioc::makebook();

The above is a specific example of container. It is better not to write a specific dependency injection method. It is better to use registry registration and get acquisition.

<?<span>php
</span><span>class</span><span> Ioc {
</span><span>/*</span><span>*
* @var 注册的依赖数组
</span><span>*/</span>
 
   <span>protected</span> <span>static</span> <span>$registry</span> = <span>array</span><span>();
 
   </span><span>/*</span><span>*
    * 添加一个resolve到registry数组中
    * @param  string $name 依赖标识
    * @param  object $resolve 一个匿名函数用来创建实例
    * @return void
    </span><span>*/</span>
   <span>public</span> <span>static</span> <span>function</span> register(<span>$name</span>, Closure <span>$resolve</span><span>)
   {
      </span><span>static</span>::<span>$registry</span>[<span>$name</span>] = <span>$resolve</span><span>;
   }
 
   </span><span>/*</span><span>*
     * 返回一个实例
     * @param  string $name 依赖的标识
     * @return mixed
     </span><span>*/</span>
   <span>public</span> <span>static</span> <span>function</span> resolve(<span>$name</span><span>)
   {
       </span><span>if</span> ( <span>static</span>::registered(<span>$name</span><span>) )
       {
          </span><span>$name</span> = <span>static</span>::<span>$registry</span>[<span>$name</span><span>];
          </span><span>return</span> <span>$name</span><span>();
       }
       </span><span>throw</span> <span>new</span> <span>Exception</span>('Nothing registered with that name, fool.'<span>);
   }
   </span><span>/*</span><span>*
    * 查询某个依赖实例是否存在
    * @param  string $name id
    * @return bool 
    </span><span>*/</span>
   <span>public</span> <span>static</span> <span>function</span> registered(<span>$name</span><span>)
   {
      </span><span>return</span> <span>array_key_exists</span>(<span>$name</span>, <span>static</span>::<span>$registry</span><span>);
   }
}</span>

You can now register and inject a

through the following methods
<?<span>php
</span><span>$book</span> = Ioc::registry('book', <span>function</span><span>(){
</span><span>$book</span> = <span>new</span><span> Book;
</span><span>$book</span>->setdb('...'<span>);
</span><span>$book</span>->setprice('...'<span>);
</span><span>return</span> <span>$book</span><span>;
});
 
</span><span>//</span><span>注入依赖</span>
<span>$book</span> = Ioc::resolve('book'<span>);
</span>?>

Reference: http://www.4wei.cn/archives/1002316

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1125521.htmlTechArticlephp dependency injection and control inversion, php injection reverse DIDependency Injection dependency injection IoCInversion of Control inversion of control requirements To understand the above two concepts, you must understand the following...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How can you check if a PHP session has already started?How can you check if a PHP session has already started?Apr 30, 2025 am 12:20 AM

In PHP, you can use session_status() or session_id() to check whether the session has started. 1) Use the session_status() function. If PHP_SESSION_ACTIVE is returned, the session has been started. 2) Use the session_id() function, if a non-empty string is returned, the session has been started. Both methods can effectively check the session state, and choosing which method to use depends on the PHP version and personal preferences.

Describe a scenario where using sessions is essential in a web application.Describe a scenario where using sessions is essential in a web application.Apr 30, 2025 am 12:16 AM

Sessionsarevitalinwebapplications,especiallyfore-commerceplatforms.Theymaintainuserdataacrossrequests,crucialforshoppingcarts,authentication,andpersonalization.InFlask,sessionscanbeimplementedusingsimplecodetomanageuserloginsanddatapersistence.

How can you manage concurrent session access in PHP?How can you manage concurrent session access in PHP?Apr 30, 2025 am 12:11 AM

Managing concurrent session access in PHP can be done by the following methods: 1. Use the database to store session data, 2. Use Redis or Memcached, 3. Implement a session locking strategy. These methods help ensure data consistency and improve concurrency performance.

What are the limitations of using PHP sessions?What are the limitations of using PHP sessions?Apr 30, 2025 am 12:04 AM

PHPsessionshaveseverallimitations:1)Storageconstraintscanleadtoperformanceissues;2)Securityvulnerabilitieslikesessionfixationattacksexist;3)Scalabilityischallengingduetoserver-specificstorage;4)Sessionexpirationmanagementcanbeproblematic;5)Datapersis

Explain how load balancing affects session management and how to address it.Explain how load balancing affects session management and how to address it.Apr 29, 2025 am 12:42 AM

Load balancing affects session management, but can be resolved with session replication, session stickiness, and centralized session storage. 1. Session Replication Copy session data between servers. 2. Session stickiness directs user requests to the same server. 3. Centralized session storage uses independent servers such as Redis to store session data to ensure data sharing.

Explain the concept of session locking.Explain the concept of session locking.Apr 29, 2025 am 12:39 AM

Sessionlockingisatechniqueusedtoensureauser'ssessionremainsexclusivetooneuseratatime.Itiscrucialforpreventingdatacorruptionandsecuritybreachesinmulti-userapplications.Sessionlockingisimplementedusingserver-sidelockingmechanisms,suchasReentrantLockinJ

Are there any alternatives to PHP sessions?Are there any alternatives to PHP sessions?Apr 29, 2025 am 12:36 AM

Alternatives to PHP sessions include Cookies, Token-based Authentication, Database-based Sessions, and Redis/Memcached. 1.Cookies manage sessions by storing data on the client, which is simple but low in security. 2.Token-based Authentication uses tokens to verify users, which is highly secure but requires additional logic. 3.Database-basedSessions stores data in the database, which has good scalability but may affect performance. 4. Redis/Memcached uses distributed cache to improve performance and scalability, but requires additional matching

Define the term 'session hijacking' in the context of PHP.Define the term 'session hijacking' in the context of PHP.Apr 29, 2025 am 12:33 AM

Sessionhijacking refers to an attacker impersonating a user by obtaining the user's sessionID. Prevention methods include: 1) encrypting communication using HTTPS; 2) verifying the source of the sessionID; 3) using a secure sessionID generation algorithm; 4) regularly updating the sessionID.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function