自定义辅助函数
入口文件加载
目录下建立一个helpers目录下建立functions.php 文件
<?phpphp
if (! function_exists('hello')) {
function hello(){
echo 'hello word';
}
}json
修改项目入口文件index.phpyii2
新增以下代码:app
require(__DIR__ . '/../helpers/functions.php');composer
composer中设置加载(推荐)yii
在 composer.json 文件里面添加以下代码:函数
"autoload": {
"files": [
"common/components/functions.php"
]
},
添加完以后,在common/components下添加文件functions.php,项目根目录下执行 composer update
ok!布局
自定义component 组件post
在app\components下新建NewComponent.phpui
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 操做