Yii2 自定义class、全局函数
1、在appcomponents下新建MyComponent.php
namespace appcomponents; use Yii; use yiiaseComponent; use yiiaseInvalidConfigException; class MyComponent extends Component { public function welcome() { echo "Hello..Welcome to MyComponent"; } }
2、在config/web.php加入你的components
"components" => [ "mycomponent" => [ "class" => "appcomponentsMyComponent", ], ]
3、在controllers/TestController.php中用你的components
namespace appcontrollers; use Yii; class TestController extends yiiwebController { public function actionWelcome() { Yii::$app->mycomponent->welcome(); }
-------------------------------------------------------------
想在每个请求处理过程都实例化某个组件即便它不会被访问, 可以将该组件ID加入到应用主体的
[[yiiaseApplication::bootstrap|bootstrap]] 属性中。
例如, 如下的应用主体配置保证了 log 组件一直被加载。
/config/web.php
$config = [
"bootstrap" => [
// 将 log 组件 ID 加入引导让它始终载入
"log",
],
"components" => [
"log" => [
// "log" 组件的配置
],
],
]
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。
- 上一篇: 怎么样捕捉在edit control中按下回车键
- 下一篇: 使用pandas读取csv文件的指定列