经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » PHP » 查看文章
Yii框架模拟组件调用注入示例
来源:jb51  时间:2019/11/12 8:29:33  对本文有异议

本文实例讲述了Yii框架模拟组件调用注入。分享给大家供大家参考,具体如下:

yii 中组件只有在被调用的时候才会被实例化,且在当前请求中之后调用该组件只会使用上一次实例化的实例,不会重新生成该实例。

  1. 'components' => array(
  2. '组件调用名' => '组件调用命名空间',
  3. '组件调用名' => array(
  4. 'class' => '组件调用命名空间'
  5. );
  6. '组件调用名' => function(){
  7. return new '组件调用命名空间';
  8. }
  9. )
  10.  

一个类似的小组件,可以实现上述功能。方便我们存储服务功能组件。

  1. <?php
  2. namespace app\components\Services;
  3. /**
  4. * 自定义服务层调用组件
  5. * 支持 的实例模式只有yii模式的string 和 array 模式
  6. * 例子
  7. * services => array(
  8. * 'customService' => array(
  9. * 'class' => 'app\components\Custom\Custom',
  10. * 'name' => '我是勇哥'
  11. * ),
  12. * )
  13. */
  14. class Services
  15. {
  16. private $dataObj = array();
  17. private $classes = array();
  18. public function __set($name,$value)
  19. {
  20. $this->classes[$name] = $value;
  21. }
  22. public function __get($name)
  23. {
  24. if(!isset($this->dataObj[$name]) || $this->dataObj[$name] == null)
  25. {
  26. $classInfo = $this->classes[$name];
  27. $this->dataObj[$name] = is_array($classInfo) ? (new $classInfo['class']) : (new $classInfo);
  28. if(is_array($classInfo))
  29. foreach($classInfo as $a=>$b)
  30. if($a != 'class')
  31. $this->dataObj[$name]->$a = $b;
  32. }
  33. return $this->dataObj[$name];
  34. }
  35. }
  36.  

web.php

  1. 'components'=>array(
  2. 'services' => array(
  3. 'class' => 'app\components\Services\Services',
  4. //自定义服务 custom1
  5. 'custom1Service' => array(
  6. 'class' => 'app\services\Custom1\Custom1',
  7. //需要注入的属性值
  8. 'name' => '我是勇哥',
  9. 'age' => 22
  10. ),
  11. //自定义服务 custom2
  12. 'custom2Service' => array(
  13. 'class' => 'app\services\Custom2\Custom2',
  14. //需要注入的属性值
  15. 'name' => '我是勇哥',
  16. 'age' => 22
  17. ),
  18. )
  19. )
  20.  

控制层调用

  1. <?php
  2. namespace app\controllers\home;
  3. use Yii;
  4. use yii\web\Controller;
  5. class IndexController extends Controller
  6. {
  7. public function actionIndex()
  8. {
  9. echo Yii::$app->services->custom1Service->name;
  10. }
  11. }
  12.  

更多关于Yii相关内容感兴趣的读者可查看jb51专题:《Yii框架入门及常用技巧总结》、《php优秀开发框架总结》、《smarty模板入门基础教程》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总

希望本文所述对大家基于Yii框架的PHP程序设计有所帮助。

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号