模組是一個有自己的模型,視圖,控制器以及其他模組的實體。這實際上是在應用程式內的應用程式。
第1步- 在你的專案根目錄內創建一個 modules 檔夾。在 modules 檔夾內創建一個名為 admin 的檔夾。這是 admin 模組的基本檔夾。
第2步 - 在 admin 檔夾裏邊,使用以下代碼來創建 Admin.php 檔。
<?php namespace app\modules\admin; class Admin extends \yii\base\Module { public function init() { parent::init(); } } ?>
我們剛剛創建了一個模組類。它位於模組根路徑下。每一次模組被訪問時,將創建對應的模組類的一個實例。init()函數用於初始化模組的屬性。
第3步 - 現在,在 admin檔夾內添加兩個目錄- controllers 和 views。添加 CustomController.php 檔到控制器的檔夾中。
<?php namespace app\modules\admin\controllers; use yii\web\Controller; class CustomController extends Controller { public function actionGreet() { return $this->render('greet'); } } ?>
當創建一個模組,慣例是把控制器類到模組根路徑的 controllers 目錄。我們剛才定義的actionGreet函數,只返回一個 greet 視圖。
在模組中視圖應該放在模組基本路徑的 views 檔夾中。如果視圖是由控制器呈現,那麼它們應位於對應於該控制器ID的檔夾中。將 custom 檔夾添加到 views 檔夾。
第4步 - 在 custom 目錄裏創建一個名為 greet.php 檔並使用下麵的代碼。
<h1>Hello,這是一個自定義模組!</h1>
我們剛剛創建了 actionGreet 視圖。要在模組中使用這個新創建檔,我們還應該配置應用程式。我們應該將模組添加到應用程式的模組屬性中。
第5步 - 修改 config/web.php 檔,如下。
<?php $params = require(__DIR__ . '/params.php'); $config = [ 'id' => 'basic', 'basePath' => dirname(__DIR__), 'bootstrap' => ['log'], 'components' => [ 'request' => [ // !!! insert a secret key in the following (if it is empty) - this is //required by cookie validation 'cookieValidationKey' => 'Yia-xuhuhu.com', ], 'cache' => [ 'class' => 'yii\caching\FileCache', ], 'user' => [ 'identityClass' => 'app\models\User', 'enableAutoLogin' => true, ], 'errorHandler' => [ 'errorAction' => 'site/error', ], 'mailer' => [ 'class' => 'yii\swiftmailer\Mailer', // send all mails to a file by default. You have to set // 'useFileTransport' to false and configure a transport // for the mailer to send real emails. 'useFileTransport' => true, ], 'log' => [ 'traceLevel' => YII_DEBUG ? 3 : 0, 'targets' => [ [ 'class' => 'yii\log\FileTarget', 'levels' => ['error', 'warning'], ], ], ], 'db' => require(__DIR__ . '/db.php'), ], 'modules' => [ 'admin' => [ 'class' => 'app\modules\admin\Admin', ], ], 'params' => $params, ]; if (YII_ENV_DEV) { // configuration adjustments for 'dev' environment $config['bootstrap'][] = 'debug'; $config['modules']['debug'] = [ 'class' => 'yii\debug\Module', ]; $config['bootstrap'][] = 'gii'; $config['modules']['gii'] = [ 'class' => 'yii\gii\Module', ]; } return $config; ?>
模組的控制器路由必須使用模組ID開始,後面控制器ID和動作ID。
第6步 - 如要在應用程式運行 actionGreet,應該使用下麵的路由
admin/custom/greet
在這裏,admin 就是一個模組ID,custom 是控制器ID和 greet 就是一個動作ID。
要點
模組(Modules)應該 −
-
在大型應用程式中。應劃分其功能分成幾個應用組。每個應用功能組可以作為一個模組開發。
-
可重複使用。一些常用的功能,如搜索引擎優化管理或博客的管理,可以開發成模組,這樣在今後的專案中很容易地重用它們。
上一篇:
Yii小部件(Widget)
下一篇:
Yii視圖