Yii框架中组件的调用注入是怎样
Admin 2022-05-28 群英技术资讯 528 次浏览
本文实例讲述了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中,字符串之间使用“点”来连接,也就是英文中的半角句号 "." 。"."是字符串连接符,可以把两个或两个以上的字符串链接成一个字符串。例如: 12345<?php$name = "PHP中文网:";$url = "www.php";echo $name . $url . ".cn";
本文主要给大家分享的是Laravel数据库读写分离的方法,Laravel数据库读写分离配置范例如下,下文还有代码分享,需要的朋友可以参考了解看看,接下来我们就直接看代码:
建立一个websocket Worker,用来维持客户端长连接;在websocket Worker内部建立一个text Worker;开启一个内部端口,方便内部系统推送数据;通过workerman,向uid的页面推送数据;返回推送结果。
swoole重启的方法:可以通过$swoole->reload(),或者\swoole_process::kill($master_pid,SIGUSR1),或者直接kill -USR1 master_pid等方法平滑重启。
今天小编就为大家分享一篇关于PHP的mysqli_stmt_init()函数讲解,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
成为群英会员,开启智能安全云计算之旅
立即注册Copyright © QY Network Company Ltd. All Rights Reserved. 2003-2020 群英 版权所有
增值电信经营许可证 : B1.B2-20140078 粤ICP备09006778号 域名注册商资质 粤 D3.1-20240008