Yii框架中组件的调用注入是怎样
Admin 2022-05-28 群英技术资讯 1427 次浏览
这篇文章主要讲解了“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实现归并排序算法的方法,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助
swoole高效的原因:1、常驻内存,避免重复加载带来的性能损耗,提升海量性能。2、协程异步,提高对I/O密集型场景并发处理能力。3、方便地开发Http、WebSocket、TCP、UDP等应用,可以与硬件通信。
如何禁止别人直接访问php文件?可以通过判断某一个常量是否被定义或定义的值是否相同,如果未被定义或值不相同则停止脚本运行。<
swoole如果想要在开机启动时,自动运行你的swoole Server,可以在/etc/rc.local文件中加入/usr/bin/php /data/webroot/www.swoole.com/server.php。
php查询mysql记录数的方法:1、使用“mysql_num_rows”函数查询mysql记录数;2、通过修改查询语句,并使用“COUNT(*)”作为查询内容实现查询mysql记录数。
成为群英会员,开启智能安全云计算之旅
立即注册关注或联系群英网络
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