只要在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');