当前位置:网站首页>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();
}
边栏推荐
- Ali vision AI training camp-day01
- Current situation of China's hydraulic cylinder industry in 2020 (with application fields, policies and regulations, supply and demand status and enterprise pattern) [figure]
- Why are life science enterprises on the cloud in succession?
- One night I worked as an XPath Terminator: XPath Helper Plus
- 二、HikariCP獲取連接流程源碼分析二
- JVM | runtime data area (heap space)
- 揭秘GES超大规模图计算引擎HyG:图切分
- Sorting out the latest data mining competition scheme!
- 一、HikariCP获取连接流程源码分析一
- MySQL view explanation
猜你喜欢

Ali visual AI training camp -day03- construction of electronic photo album (face and expression recognition)

Connecting PHP to MySQL instances in the lamp environment of alicloud's liunx system

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

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

Apifox simple understanding -- the integrator of web side testing

广州华锐互动VR全景为各行各业带来发展

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

Bloom filter

ECS 7-day practical training camp (Advanced route) -- day03 -- ecs+slb load balancing practice

ECS 7-day practical training camp (Advanced route) -- day04 -- build a portal using ECs and polardb
随机推荐
Process of vacuum and vacuum full
广州华锐互动VR全景为各行各业带来发展
Analyse du code source du processus d'acquisition et de connexion hikaricp II
Analysis on development status and development suggestions of e-commerce industry in Xinjiang in 2020 [figure]
QQ机器人:群成员自我禁言管理【最新beta2版本】
揭秘GES超大规模图计算引擎HyG:图切分
Do you want to know how new investors open accounts? Is online account opening safe?
云上弹性高性能计算,支持生命科学产业高速发展、降本增效
Tcp/ip test questions (V)
Analysis on China's aluminum foil output, trade and enterprise leading operation in 2021: dongyangguang aluminum foil output is stable [figure]
2020-12-09 laravel . Env file loading mechanism process
Ali visual AI training camp -day05- creativity day - your image recognition project
Elastic high-performance computing on the cloud supports the rapid development of the life science industry, reducing costs and increasing efficiency
LNMP compilation and installation
Vulnhub range - darkhole 1
QQ机器人疫情查询/疫情关注等【最新beta2版本】
Solidity date tool
ECS 7-day practical training camp (Advanced route) -- day03 -- ecs+slb load balancing practice
PostgreSQL change table owner
Many varieties of EA can be used