Yii框架中组件的调用注入是怎样
Admin 2022-05-28 群英技术资讯 1007 次浏览
这篇文章主要讲解了“Yii框架中组件的调用注入是怎样”,文中的讲解内容简单、清晰、详细,对大家学习或是工作可能会有一定的帮助,希望大家阅读完这篇文章能有所收获。下面就请大家跟着小编的思路一起来学习一下吧。本文实例讲述了Yii框架模拟组件调用注入。分享给大家供大家参考,具体如下:
yii 中组件只有在被调用的时候才会被实例化,且在当前请求中之后调用该组件只会使用上一次实例化的实例,不会重新生成该实例。
'components' => array(
'组件调用名' => '组件调用命名空间',
'组件调用名' => array(
'class' => '组件调用命名空间'
);
'组件调用名' => function(){
return new '组件调用命名空间';
}
)
一个类似的小组件,可以实现上述功能。方便我们存储服务功能组件。
<?php
namespace app\components\Services;
/**
* 自定义服务层调用组件
* 支持 的实例模式只有yii模式的string 和 array 模式
* 例子
* services => array(
* 'customService' => array(
* 'class' => 'app\components\Custom\Custom',
* 'name' => '我是勇哥'
* ),
* )
*/
class Services
{
private $dataObj = array();
private $classes = array();
public function __set($name,$value)
{
$this->classes[$name] = $value;
}
public function __get($name)
{
if(!isset($this->dataObj[$name]) || $this->dataObj[$name] == null)
{
$classInfo = $this->classes[$name];
$this->dataObj[$name] = is_array($classInfo) ? (new $classInfo['class']) : (new $classInfo);
if(is_array($classInfo))
foreach($classInfo as $a=>$b)
if($a != 'class')
$this->dataObj[$name]->$a = $b;
}
return $this->dataObj[$name];
}
}
web.php
'components'=>array(
'services' => array(
'class' => 'app\components\Services\Services',
//自定义服务 custom1
'custom1Service' => array(
'class' => 'app\services\Custom1\Custom1',
//需要注入的属性值
'name' => '我是勇哥',
'age' => 22
),
//自定义服务 custom2
'custom2Service' => array(
'class' => 'app\services\Custom2\Custom2',
//需要注入的属性值
'name' => '我是勇哥',
'age' => 22
),
)
)
控制层调用
<?php
namespace app\controllers\home;
use Yii;
use yii\web\Controller;
class IndexController extends Controller
{
public function actionIndex()
{
echo Yii::$app->services->custom1Service->name;
}
}
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
猜你喜欢
这篇文章主要介绍了PHP封装请求类,结合实例形式分析了基于Yii框架的curl封装请求处理的相关实现技巧,需要的朋友可以参考下
这篇文章主要介绍了Laravel框架基础语法与知识点整理,包括模板变量、输出、include引入子视图等相关操作技巧,需要的朋友可以参考下
有些朋友想要将ppt转jpg图片来查看,那么这要怎样实现呢?其实实现这个并不困难,下面小编就给大家分享用PHP实现ppt转jpg图片的功能的代码,有需要的朋友可以参考。
可在内部迭代自己的外部迭代器或类的接口。接口摘要IteratorextendsTraversable{/*方法*/abstractpublicmixedcurrent(void)abstractpublics...
如何用php获取当前日期的7天内的时间,比如今天是5号,我想获取5号前7天的日期,怎么获取?实现方法如下:如何用php获取当前日期的7天内的时间实现方法如下:$t=time()+3600*8;//这里和标准时间相差8小时需要补足$tget=$t-3600*24*5;//比如5天前的时间echodate("Y-m-dH:i:s星期w",$tget);//格式按你需要选取例:$che
成为群英会员,开启智能安全云计算之旅
立即注册关注或联系群英网络
7x24小时售前:400-678-4567
7x24小时售后:0668-2555666
24小时QQ客服
群英微信公众号
CNNIC域名投诉举报处理平台
服务电话:010-58813000
服务邮箱:service@cnnic.cn
投诉与建议:0668-2555555
Copyright © QY Network Company Ltd. All Rights Reserved. 2003-2020 群英 版权所有
增值电信经营许可证 : B1.B2-20140078 ICP核准(ICP备案)粤ICP备09006778号 域名注册商资质 粤 D3.1-20240008