


Detailed explanation of how PHP implements automatic dependency injection based on reflection mechanism
This article mainly introduces the method of automatic dependency injection in PHP based on the reflection mechanism. It analyzes the steps, principles and related operating techniques of using reflection to realize automatic dependency injection in PHP in the form of examples. Friends in need can refer to it
Dependency injection is also called inversion of control. Anyone who has used the framework should be familiar with it. Many people think it is something very high-end when they see the name, and are daunted by it. Today I took the time to do some research and unravel its mystery. Without further ado, let’s go straight to the code;
/** * * 工具类,使用该类来实现自动依赖注入。 * */ class Ioc { // 获得类的对象实例 public static function getInstance($className) { $paramArr = self::getMethodParams($className); return (new ReflectionClass($className))->newInstanceArgs($paramArr); } /** * 执行类的方法 * @param [type] $className [类名] * @param [type] $methodName [方法名称] * @param [type] $params [额外的参数] * @return [type] [description] */ public static function make($className, $methodName, $params = []) { // 获取类的实例 $instance = self::getInstance($className); // 获取该方法所需要依赖注入的参数 $paramArr = self::getMethodParams($className, $methodName); return $instance->{$methodName}(...array_merge($paramArr, $params)); } /** * 获得类的方法参数,只获得有类型的参数 * @param [type] $className [description] * @param [type] $methodsName [description] * @return [type] [description] */ protected static function getMethodParams($className, $methodsName = '__construct') { // 通过反射获得该类 $class = new ReflectionClass($className); $paramArr = []; // 记录参数,和参数类型 // 判断该类是否有构造函数 if ($class->hasMethod($methodsName)) { // 获得构造函数 $construct = $class->getMethod($methodsName); // 判断构造函数是否有参数 $params = $construct->getParameters(); if (count($params) > 0) { // 判断参数类型 foreach ($params as $key => $param) { if ($paramClass = $param->getClass()) { // 获得参数类型名称 $paramClassName = $paramClass->getName(); // 获得参数类型 $args = self::getMethodParams($paramClassName); $paramArr[] = (new ReflectionClass($paramClass->getName()))->newInstanceArgs($args); } } } } return $paramArr; } }
The above code uses the reflection function of PHP to create a container class and use this class to Implement dependency injection functions for other classes. The above dependency injection is divided into two types, one is dependency injection of constructor, and the other is dependency injection of method. We use the following three classes for testing.
class A { protected $cObj; /** * 用于测试多级依赖注入 B依赖A,A依赖C * @param C $c [description] */ public function __construct(C $c) { $this->cObj = $c; } public function aa() { echo 'this is A->test'; } public function aac() { $this->cObj->cc(); } } class B { protected $aObj; /** * 测试构造函数依赖注入 * @param A $a [使用引来注入A] */ public function __construct(A $a) { $this->aObj = $a; } /** * [测试方法调用依赖注入] * @param C $c [依赖注入C] * @param string $b [这个是自己手动填写的参数] * @return [type] [description] */ public function bb(C $c, $b) { $c->cc(); echo "\r\n"; echo 'params:' . $b; } /** * 验证依赖注入是否成功 * @return [type] [description] */ public function bbb() { $this->aObj->aac(); } } class C { public function cc() { echo 'this is C->cc'; } }
// 使用Ioc来创建B类的实例,B的构造函数依赖A类,A的构造函数依赖C类。 $bObj = Ioc::getInstance('B'); $bObj->bbb(); // 输出:this is C->cc , 说明依赖注入成功。 // 打印$bObj var_dump($bObj); // 打印结果,可以看出B中有A实例,A中有C实例,说明依赖注入成功。 object(B)#3 (1) { ["aObj":protected]=> object(A)#7 (1) { ["cObj":protected]=> object(C)#10 (0) { } } }Test method dependency injection
Ioc::make('B', 'bb', ['this is param b']); // 输出结果,可以看出依赖注入成功。 this is C->cc params:this is param b
Related reading:
PHP Reflection usage example code
PHP reflection mechanism code to implement dynamic proxy
The above is the detailed content of Detailed explanation of how PHP implements automatic dependency injection based on reflection mechanism. For more information, please follow other related articles on the PHP Chinese website!

DependencyInjection(DI)inPHPenhancescodeflexibilityandtestabilitybydecouplingdependencycreationfromusage.ToimplementDIeffectively:1)UseDIcontainersjudiciouslytoavoidover-engineering.2)Avoidconstructoroverloadbylimitingdependenciestothreeorfour.3)Adhe

ToimproveyourPHPwebsite'sperformance,usethesestrategies:1)ImplementopcodecachingwithOPcachetospeedupscriptinterpretation.2)Optimizedatabasequeriesbyselectingonlynecessaryfields.3)UsecachingsystemslikeRedisorMemcachedtoreducedatabaseload.4)Applyasynch

Yes,itispossibletosendmassemailswithPHP.1)UselibrarieslikePHPMailerorSwiftMailerforefficientemailsending.2)Implementdelaysbetweenemailstoavoidspamflags.3)Personalizeemailsusingdynamiccontenttoimproveengagement.4)UsequeuesystemslikeRabbitMQorRedisforb

DependencyInjection(DI)inPHPisadesignpatternthatachievesInversionofControl(IoC)byallowingdependenciestobeinjectedintoclasses,enhancingmodularity,testability,andflexibility.DIdecouplesclassesfromspecificimplementations,makingcodemoremanageableandadapt

The best ways to send emails using PHP include: 1. Use PHP's mail() function to basic sending; 2. Use PHPMailer library to send more complex HTML mail; 3. Use transactional mail services such as SendGrid to improve reliability and analysis capabilities. With these methods, you can ensure that emails not only reach the inbox, but also attract recipients.

Calculating the total number of elements in a PHP multidimensional array can be done using recursive or iterative methods. 1. The recursive method counts by traversing the array and recursively processing nested arrays. 2. The iterative method uses the stack to simulate recursion to avoid depth problems. 3. The array_walk_recursive function can also be implemented, but it requires manual counting.

In PHP, the characteristic of a do-while loop is to ensure that the loop body is executed at least once, and then decide whether to continue the loop based on the conditions. 1) It executes the loop body before conditional checking, suitable for scenarios where operations need to be performed at least once, such as user input verification and menu systems. 2) However, the syntax of the do-while loop can cause confusion among newbies and may add unnecessary performance overhead.

Efficient hashing strings in PHP can use the following methods: 1. Use the md5 function for fast hashing, but is not suitable for password storage. 2. Use the sha256 function to improve security. 3. Use the password_hash function to process passwords to provide the highest security and convenience.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

SublimeText3 English version
Recommended: Win version, supports code prompts!

Notepad++7.3.1
Easy-to-use and free code editor

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.
