yii2 应用组件 components
只要在components配置了相关组件,在整个yii2项目中就可以用\Yii::$app->xxx来访问。
补充:请谨慎注册太多应用组件,应用组件就像全局变量,使用太多可能加大测试和维护的难度。 一般情况下可以在需要时再创建本地组件。
第一步先建立一个组件
common/components/ShortMsgService.php
classShortMsgServiceextendsComponent{public$accessKey;publicfunctionint(){parent::init();}publicfunctionsend($phone,$message){echo$this->accessKey,$phone,$message;}}
第二步配置加载组件
common/config/main.php
return['vendorPath'=>dirname(dirname(__DIR__)).'/vendor','components'=>['cache'=>['class'=>'yii\caching\FileCache',],'ShortMsgService'=>['class'=>'common\components\ShortMsgService','accessKey'=>'accessKeyHere',],],];
第三步在控制器中尝试使用组件
$sms=Yii::$app->ShortMsgService;$sms->send('18588888888','Areyouok');
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。