Yii模塊(Modules)

模塊是一個有自己的模型,視圖,控制器以及其它模塊的實體。這實際上是在應用程序內的應用程序。

第1步- 在你的項目根目錄內創建一個 modules 文件夾。在 modules 文件夾內創建一個名爲 admin 的文件夾。這是 admin 模塊的基本文件夾。

第2步 - 在 admin 文件夾裏邊,使用以下代碼來創建 Admin.php 文件。

 

我們剛剛創建了一個模塊類。它位於模塊根路徑下。每一次模塊被訪問時,將創建對應的模塊類的一個實例。init()函數用於初始化模塊的屬性。

第3步 - 現在,在 admin文件夾內添加兩個目錄- controllers 和 views。添加 CustomController.php 文件到控制器的文件夾中。

render('greet'); } } ?>

 

當創建一個模塊,慣例是把控制器類到模塊根路徑的 controllers 目錄。我們剛纔定義的actionGreet函數,只返回一個 greet 視圖。

在模塊中視圖應該放在模塊基本路徑的 views 文件夾中。如果視圖是由控制器呈現,那麼它們應位於對應於該控制器ID的文件夾中。將 custom 文件夾添加到 views 文件夾。

第4步 - 在 custom 目錄裏創建一個名爲 greet.php 文件並使用下面的代碼。

Hello,這是一個自定義模塊!

 

我們剛剛創建了 actionGreet 視圖。要在模塊中使用這個新創建文件,我們還應該配置應用程序。我們應該將模塊添加到應用程序的模塊屬性中。

第5步 - 修改 config/web.php 文件,如下。

'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-yiibai.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。

第7步- 現在,鍵入URL訪問:  http://localhost:8080/index.php?r=admin/custom/greet,就會看到下面的輸出結果了。
Yii模塊(Modules)

要點

模塊(Modules)應該 −

  • 在大型應用程序中。應劃分其功能分成幾個應用組。每個應用功能組可以作爲一個模塊開發。

  • 可重複使用。一些常用的功能,如搜索引擎優化管理或博客的管理,可以開發成模塊,這樣在今後的項目中很容易地重用它們。