yii2 扩展和自定义(函数 , 组件 , 模块)
入口文件加载
目录下创建一个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"
]
},
ok!
在appcomponents下新建NewComponent.php
use Yii;
use yiiaseComponent;
use yiiaseInvalidConfigException;
class NewComponent extends Component
{
public function hello()
{
echo "hello world";
}
}
main.php配置文件中 "components" => [
"testcomponent" => [
"class" => "appcomponentsMyComponent",
],
]
下面就可以愉快的使用 组件了是不是很简单 !
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 appmodulesforum;
class Module extends yiiaseModule
{
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
],
];
使用模块 要在应用中使用模块,只需要将模块加入到应用主体配置的yiiaseApplication::modules属性的列表中, 如下代码的应用主体配置 使用 forum 模块:
[
"modules" => [
"forum" => [
"class" => "appmodulesforumModule",
// ... 模块其他配置 ...
],
],
]
访问路由 forum/post/index 代表模块中 post 控制器的 index 操作
就是这么简单 !
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。