之前,由於所要訪問的controller都是位於根目錄下的controllers目錄下,就像下面這樣:
此時,我們可以直接通過 localhost/basic/web/index.php?r=dao/index 來訪問圖中DaoController.php里的actionIndex。
但是如果,我們將controller、view等有關聯的獨立出來作為一個模塊Modules,那么又將怎樣去處理呢。
就像上面這樣,這個Site控制器里面的action又將如何訪問呢。
1.建立目錄
首先建立如上的目錄結構,在api下的以及目錄有三個文件夾和一個文件Module.php,這個php文件內容如下:
<?php namespace app\modules\api; /** * api module definition class */ class Module extends \yii\base\Module { /** * @inheritdoc */ public $controllerNamespace = 'app\modules\api\controllers'; /** * @inheritdoc */ public function init() { parent::init(); // custom initialization code goes here } }
這個文件可以直接復制,無需作任何修改,只是注意紅字部分的命名空間,不要寫錯了!
2.web.php
還記得項目根目錄下的config文件夾下有個web.php文件么,添加如下字段:
<?php $params = require __DIR__ . '/params.php'; $db = require __DIR__ . '/db.php'; $config = [ 'id' => 'basic', 'basePath' => dirname(__DIR__), 'bootstrap' => ['log'], 'aliases' => [ '@bower' => '@vendor/bower-asset', '@npm' => '@vendor/npm-asset', ], 'components' => [ 'request' => [ // !!! insert a secret key in the following (if it is empty) - this is required by cookie validation 'cookieValidationKey' => 'jjsYJ_ju0W8ifOv5mY3JBMI6DOppFlo6', ], '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' => $db, /* 'urlManager' => [ 'enablePrettyUrl' => true, 'showScriptName' => false, 'rules' => [ ], ], */ ], 'modules' => [ 'api' => [ 'class' => 'app\modules\api\Module', ], ], 'params' => $params, ]; if (YII_ENV_DEV) { // configuration adjustments for 'dev' environment $config['bootstrap'][] = 'debug'; $config['modules']['debug'] = [ 'class' => 'yii\debug\Module', // uncomment the following to add your IP if you are not connecting from localhost. //'allowedIPs' => ['127.0.0.1', '::1'], ]; $config['bootstrap'][] = 'gii'; $config['modules']['gii'] = [ 'class' => 'yii\gii\Module', // uncomment the following to add your IP if you are not connecting from localhost. //'allowedIPs' => ['127.0.0.1', '::1'], ]; } return $config;
為了避免看的時候出錯,上面紅字的“鍵”是出於同一級的,紅字加粗的是我們為modules添加的相關配置信息,相當於在應用中注冊了剛才定義的組件(api)。
3.api組件下的controllers
現在我們在Modules/api/controllers下新建一個SiteControllers.php,內容如下:
<?php namespace app\modules\api\controllers; use yii\web\Controller; class SiteController extends Controller { public function actionIndex() { echo "hello world"; } }
注意命名空間就好~~~
4.瀏覽器訪問
最后就是瀏覽器訪問這個actionIndex了,瀏覽器輸入: http://localhost/basic/web/index.php?r=api/site/index
至此,結束~~~