[PHP] 使用反射实现的控制反转
2023-02-18 15:46:59 时间
搬家进程中反射实现控制反转,样做的好处是可以通过配置项动态的控制下面那个类的属性
1.$this->getObject($class, $config->getConfig('param'), array($this), $interfaces);
2.$reflection=new ReflectionClass($class);
3.$reflection->implementsInterface($interface)//检测是否实现接口
4.$obj=$reflection->newInstanceArgs()
5.$reflection->hasMethod($method)//检测是否有这个方法
6.$obj->$method($v);
举例:
/* 这样做的好处是可以通过配置项动态的控制下面那个类的属性 */ //配置项 $conf=array( 'class'=>'User', 'newParams'=>array('name'=>'taoshihan'), 'setParams'=>array( 'score'=>'100fen', 'age'=>'100' ) ); //业务类 class User { private $name; private $age; private $score; public function __construct($name){ $this->name=$name; } public function setAge($age){ $this->age=$age; } public function setScore($score){ $this->score=$score; } } //生成对象 class Application{ private $conf; public function __construct($conf){ $this->conf=$conf; } public function getAction(){ $obj=$this->getObject($this->conf['class'],$this->conf['setParams'],$this->conf['newParams']); return $obj; } public function getObject($class, $setParams = null, $newParams = array()){ if (!$class) { return null; } $reflection = new ReflectionClass($class); $obj = $reflection->newInstanceArgs($newParams); if (!empty($setParams)) { foreach ($setParams as $k => $v) { $method = 'set' . ucfirst($k); if ($reflection->hasMethod($method)) { $obj->$method($v); }} } return $obj; } } $app=new Application($conf); $obj=$app->getAction(); var_dump($obj);
各个属性正确赋值:
相关文章
- 小菜学习设计模式(三)—工厂方法(Factory Method)模式
- 小菜学习Winform(二)WMPLib实现音乐播放器
- 小菜学习设计模式(二)—单例(Singleton)模式
- 小菜学习设计模式(一)—模板方法(Template)模式
- .Net中DataAdapter批量插入和更新数据总结
- ELK 架构之 Logstash 和 Filebeat 安装配置
- 确定稳定的 Spring Cloud 相关环境版本
- IdentityServer4 SigningCredential(RSA 证书加密)
- ASP.NET WebApi JObject 使用
- Consul 服务注册与服务发现
- EntityFramework.Extended 支持 MySql
- JQuery 复制粘贴上传图片插件(textarea 和 tinyMCE)
- ASP.NET 5 单元测试中使用依赖注入
- ASP.NET Web API 异常日志记录
- Windows 搭建 .NET 跨平台环境并运行应用程序
- IDDD 实现领域驱动设计-理解领域和子域
- 【续集】塞翁失马,焉知非福:由 Styles.Render 所引发 runAllManagedModulesForAllRequests="true" 的思考
- DDD 领域驱动设计-“臆想”中的实体和值对象
- DDD 领域驱动设计-三个问题思考实体和值对象(续)
- EF Code First 一对多、多对多关联,如何加载子集合?