首页 > 代码库 > [moka同学笔记]Yii2 自定义class、自定义全局函数(摘录)

[moka同学笔记]Yii2 自定义class、自定义全局函数(摘录)

1、在app\components下新建MyComponent.PHP

    namespace app\components;  
       
       
    use Yii;  
    use yii\base\Component;  
    use yii\base\InvalidConfigException;  
       
    class MyComponent extends Component  
    {  
     public function welcome()  
     {  
      echo "Hello..Welcome to MyComponent";  
     }  
       
    }


2、在config/web.php加入你的components

‘components‘ => [  
   
         ‘mycomponent‘ => [  
   
            ‘class‘ => ‘app\components\MyComponent‘,  
   
            ],  
           ] 

 

 

3、在controllers/TestController.php中用你的components

namespace app\controllers;  
use Yii;  
   
class TestController extends \yii\web\Controller  
{  
    public function actionWelcome()  
    {  
       Yii::$app->mycomponent->welcome();  
    }  
   
} 

 

 

[moka同学笔记]Yii2 自定义class、自定义全局函数(摘录)