首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >yii2 扩展和自定义(函数 , 组件 , 模块)

yii2 扩展和自定义(函数 , 组件 , 模块)

作者头像
botkenni
发布于 2019-09-02 16:13:40
发布于 2019-09-02 16:13:40
1.4K0
举报
文章被收录于专栏:IT码农IT码农

自定义辅助函数 入口文件加载 目录下创建一个helpers目录下创建functions.php 文件 <?php

if (! function_exists('hello')) { function hello(){ echo 'hello word'; } }

修改项目入口文件index.php

新增如下代码:

require(__DIR__ . '/../helpers/functions.php');

composer中设置加载(推荐)

在 composer.json 文件里面添加如下代码:

"autoload": { "files": [ "common/components/functions.php" ] }, 添加完之后,在common/components下添加文件functions.php,项目根目录下执行 composer update ok!

自定义component 组件

在app\components下新建NewComponent.php

namespace app\components; use Yii; use yii\base\Component; use yii\base\InvalidConfigException; class NewComponent extends Component { public function hello() { echo "hello world"; } } main.php配置文件中 'components' => [ 'testcomponent' => [ 'class' => 'app\components\MyComponent', ], ]

下面就可以愉快的使用 组件了是不是很简单 !

Yii::$app->testcomponent->hello();

自定义Modules 模块 以下参考yii2.0 权威指南

新建一个如下目录 forum/ Module.php 模块类文件 controllers/ 包含控制器类文件 DefaultController.php default 控制器类文件 models/ 包含模型类文件 views/ 包含控制器视图文件和布局文件 layouts/ 包含布局文件 default/ 包含DefaultController控制器视图文件 index.php index视图文件

Module.php 代码如下

namespace app\modules\forum;

class Module extends \yii\base\Module { public function init() { parent::init();

$this->params['foo'] = 'bar'; // ... 其他初始化代码 ... } }

如果 init() 方法包含很多初始化模块属性代码, 可将他们保存在配置 并在init()中使用以下代码加载: public function init() { parent::init(); // 从config.php加载配置来初始化模块 \Yii::configure($this, require(__DIR__ . '/config.php')); } config.php配置文件可能包含以下内容,类似应用主体配置. <?php return [ 'components' => [ // list of component configurations ], 'params' => [ // list of parameters ], ];

使用模块 要在应用中使用模块,只需要将模块加入到应用主体配置的yii\base\Application::modules属性的列表中, 如下代码的应用主体配置 使用 forum 模块: [ 'modules' => [ 'forum' => [ 'class' => 'app\modules\forum\Module', // ... 模块其他配置 ... ], ], ]

访问路由 forum/post/index 代表模块中 post 控制器的 index 操作

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档