yii2 配置bootstrap使用

yii2 配置bootstrap使用

配置 config/web.php 添加 people

<?php
...
$config = [
   ...
    'bootstrap' => ['log','people'],
    ...
    'components' => [
        'people'=> [
            'class'=>'app\services\People',
                'name' => '张三',
                'age' => 17
            ],
        ],
    ...
];


return $config;

people类文件

<?php
namespace app\services;

use yii\base\Application;
use yii\base\BootstrapInterface;

class People implements BootstrapInterface{
    //姓名
    public $name;
    //年龄
    public $age;

    public function showMsg(){
        echo '欢迎' . $this->name .',你的年龄是' .$this->age;
    }

    public function bootstrap($app)
    {
        $app->on(Application::EVENT_BEFORE_REQUEST, function () {
            echo $this->showMsg();
        });
    }
}

访问

http://www.yii2.com/site/test

结果

欢迎张三,你的年龄是17
posted @ 2024-03-30 10:57  胡勇健  阅读(68)  评论(0)    收藏  举报