当前位置:网站首页>Dependency injection in PHP reflection implementation framework
Dependency injection in PHP reflection implementation framework
2022-06-25 19:16:00 【kankan231】
In the use of tp perhaps lavarel And other frameworks will see technologies such as dependency injection , It's actually used PHP The dynamic creation of object instances is realized by the reflection mechanism of , Let's simulate , The code is as follows :
/**
*
* Tool class , Use this class to implement automatic dependency injection .
*
*/
class Ioc {
// Gets the object instance of the class
public static function getInstance($className) {
$paramArr = self::getMethodParams($className);
return (new ReflectionClass($className))->newInstanceArgs($paramArr);
}
/**
* Methods that execute classes
* @param [type] $className [ Class name ]
* @param [type] $methodName [ Method name ]
* @param [type] $params [ Additional parameters ]
* @return [type] [description]
*/
public static function make($className, $methodName, $params = []) {
// Get an instance of the class
$instance = self::getInstance($className);
// Get the parameters of dependency injection required by the method
$paramArr = self::getMethodParams($className, $methodName);
$ret = $instance->{$methodName}(...array_merge($paramArr, $params));
return $ret;
}
/**
* Get the method parameters of the class , Only get parameters of type
* @param [type] $className [description]
* @param [type] $methodsName [description]
* @return [type] [description]
*/
protected static function getMethodParams($className, $methodsName = '__construct') {
// This class is obtained by reflection
$class = new ReflectionClass($className);
$paramArr = []; // Record parameters , And parameter types
// Determine whether the class has this method
if ($class->hasMethod($methodsName)) {
// Get this method
$method = $class->getMethod($methodsName);
// Determine whether the method has parameters
$params = $method->getParameters();
if (count($params) > 0) {
// Judge parameter type
foreach ($params as $key => $param) {
if ($paramClass = $param->getClass()) {
// Get the parameter type name
$paramClassName = $paramClass->getName();
// Get parameter type
$args = self::getMethodParams($paramClassName);
$paramArr[] = (new ReflectionClass($paramClass->getName()))->newInstanceArgs($args);
}
}
}
}
return $paramArr;
}
}
//User controller
class UserController{
public function detail(Request $req){
echo $req->param('id');
}
}
// Request class
class Request{
protected $params = [
'id' => 100,
];
public function param($name){
return isset($this->params[$name]) ? $this->params[$name] : null;
}
}
// call UserController->detail() Method
try {
Ioc::make(UserController::class,'detail');
} catch (\Exception $th) {
echo $th->getMessage();
}
边栏推荐
- Network security detection and prevention exercises (III)
- mysql事务讲解
- 最新數據挖掘賽事方案梳理!
- Analysis on development status and development suggestions of e-commerce industry in Xinjiang in 2020 [figure]
- Genicam gentl standard ver1.5 (1)
- Analyse du code source du processus d'acquisition et de connexion hikaricp II
- Principles of MySQL clustered index and non clustered index
- 【历史上的今天】6 月 25 日:笔记本之父诞生;Windows 98 发布;通用产品代码首次商用
- Leetcode-78-subset
- Google cloud SSH enable root password login
猜你喜欢

PHP synchronizes website content to hundreds of websites to improve SEO ranking

Mail monitoring cloud script execution progress

Embark on a new journey and reach the world with wisdom
![Current situation of China's hydraulic cylinder industry in 2020 (with application fields, policies and regulations, supply and demand status and enterprise pattern) [figure]](/img/2e/439b5dce9634d4015430c9cf06c5de.jpg)
Current situation of China's hydraulic cylinder industry in 2020 (with application fields, policies and regulations, supply and demand status and enterprise pattern) [figure]

SEO outsourcing reliable company, enterprise SEO outsourcing company which reliable?

Principles of MySQL clustered index and non clustered index

谈谈CNN中的位置和尺度问题

QQ机器人:群成员自我禁言管理【最新beta2版本】

wooyun-2014-065513

削足适履 - 谈谈赛道上的坡道改造
随机推荐
LeetCode-101-对称二叉树
QQ机器人官方插件加载配置方法【beta2版本】
QQ机器人:群成员自我禁言管理【最新beta2版本】
QQ robot epidemic situation query / epidemic situation concern [latest beta2 version]
6、 Configuration resolution of hikariconfig
Huawei released two promotion plans to promote AI talent development and scientific research innovation
广州华锐互动打造VR展厅全景在线虚拟展厅
Sorting out the latest data mining competition scheme!
Analysis on the market scale and pattern of contrast agents in China in 2021: Jiangsu Hengrui pharmaceutical, general electric, Yangzijiang Pharmaceutical Group, Bayer and bleco account for more than
PostgreSQL division considerations
Idea common plug-ins
Ali vision AI training camp-day01
R language plot visualization: plot visualization of two-dimensional histogram contour (basic 2D histogram contour)
Process of vacuum and vacuum full
Lilda Bluetooth air conditioning receiver helps create a more comfortable road life
二、HikariCP獲取連接流程源碼分析二
MySQL transaction explanation
User management and permissions
PostgreSQL user role permissions
Guangzhou Sinovel interactive creates VR Exhibition Hall panoramic online virtual exhibition hall