Yii2 自定义class、全局函数

来源:互联网 发布:java破解网站验证码 编辑:程序博客网 时间:2024/05/24 01:43

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();    } 


-------------------------------------------------------------

想在每个请求处理过程都实例化某个组件即便它不会被访问, 可以将该组件ID加入到应用主体的
    [[yii\base\Application::bootstrap|bootstrap]] 属性中。
    例如, 如下的应用主体配置保证了 log 组件一直被加载。

   /config/web.php

    $config = [
        'bootstrap' => [
            // 将 log 组件 ID 加入引导让它始终载入
            'log',
        ],
        'components' => [
            'log' => [
                // "log" 组件的配置
            ],
        ],
    ]



0 0
原创粉丝点击