Home > Article > Backend Development > Detailed explanation of the Controller controller in PHP's Yii framework, yiicontroller_PHP tutorial
controller is part of the MVC pattern. It is an object that inherits the yiibaseController class and is responsible for processing requests and generating responses. Specifically, after taking over control from the application body, the controller analyzes the request data and transmits it to the model, transmits the model results to the view, and finally generates output response information.
Operation
A controller is composed of operations, which are the most basic unit for executing end-user requests. A controller can have one or more operations.
The following example shows a controller post containing two operations view and create:
namespace app\controllers; use Yii; use app\models\Post; use yii\web\Controller; use yii\web\NotFoundHttpException; class PostController extends Controller { public function actionView($id) { $model = Post::findOne($id); if ($model === null) { throw new NotFoundHttpException; } return $this->render('view', [ 'model' => $model, ]); } public function actionCreate() { $model = new Post; if ($model->load(Yii::$app->request->post()) && $model->save()) { return $this->redirect(['view', 'id' => $model->id]); } else { return $this->render('create', [ 'model' => $model, ]); } } }
In the operation view (defined as the actionView() method), the code first loads the model according to the request model ID. If the loading is successful, the view named view will be rendered and displayed, otherwise an exception will be thrown.
In the operation create (defined as actionCreate() method), the code is similar. First fill the request data into the model, and then save the model. If both are successful, it will jump to the view operation with the ID of the newly created model. , otherwise display the create view that provides user input.
Routing
End users find actions through so-called routes, which are strings containing the following parts:
The route uses the following format:
ControllerID/ActionID
If it belongs to a controller under a module, use the following format:
ModuleID/ControllerID/ActionID
If the user's request address is http://hostname/index.php?r=site/index, the index operation of the site controller will be executed.
Create Controller
In yiiwebApplication web application, the controller should inherit yiiwebController or its subclass. Similarly, in the yiiconsoleApplication console application, the controller inherits yiiconsoleController or its subclasses. The following code defines a site controller:
namespace app\controllers; use yii\web\Controller; class SiteController extends Controller { }
Controller ID
Usually, the controller is used to handle the resource type related to the request, so the controller ID is usually a noun related to the resource. For example, use article as the controller ID for processing articles.
The controller ID should only contain English lowercase letters, numbers, underscores, dashes, and forward slashes. For example, article and post-comment are real controller IDs, and article?, PostComment, and adminpost are not controller IDs.
The controller ID can include a subdirectory prefix, for example, admin/article represents the article controller in the admin subdirectory under the yiibaseApplication::controllerNamespace controller namespace. The subdirectory prefix can be English uppercase and lowercase letters, numbers, underscores, and forward slashes. The forward slashes are used to distinguish multi-level subdirectories (such as panels/admin).
Controller class naming
The controller ID follows the following rules to derive the controller class name:
Convert the first letter of each word separated by a forward slash to uppercase. Note that if the controller ID contains a forward slash, only the first letter after the last forward slash will be converted to uppercase;
Remove the dash and replace forward slashes with backslashes;
Add Controller suffix;
Add yiibaseApplication::controllerNamespace controller namespace in front.
The following are some examples, assuming that the yiibaseApplication::controllerNamespace controller namespace is appcontrollers:
Controller classes must be automatically loaded, so in the above example, the controller article class should be defined in a file with the alias @app/controllers/ArticleController.php, and the controller admin/post2-comment should be defined in @ in the app/controllers/admin/Post2CommentController.php file.
Supplement: The last example admin/post2-comment means that you can place the controller in a subdirectory under the yiibaseApplication::controllerNamespace controller namespace, and classify the controller when you don’t want to use modules. This The method is very useful.
Controller Deployment
You can configure yiibaseApplication::controllerMap to force the above controller ID and class name to correspond. It is usually used for controllers that cannot control the class name when using a third party.
Configure application configuration in application configuration, as shown below:
[ 'controllerMap' => [ // 用类名申明 "account" 控制器 'account' => 'app\controllers\UserController', // 用配置数组申明 "article" 控制器 'article' => [ 'class' => 'app\controllers\PostController', 'enableCsrfValidation' => false, ], ], ]
Default Controller
Each application has a default controller specified by the yiibaseApplication::defaultRoute attribute; when the request does not specify a route, the attribute value is used as the route. For the yiiwebApplication web application, its value is 'site', and for the yiiconsoleApplication console application, its value is help, so the URL is http://hostname/index.php which means it is handled by the site controller.
可以在 应用配置 中修改默认控制器,如下所示:
[ 'defaultRoute' => 'main', ]
创建操作
创建操作可简单地在控制器类中定义所谓的 操作方法 来完成,操作方法必须是以action开头的公有方法。 操作方法的返回值会作为响应数据发送给终端用户,如下代码定义了两个操作 index 和 hello-world:
namespace app\controllers; use yii\web\Controller; class SiteController extends Controller { public function actionIndex() { return $this->render('index'); } public function actionHelloWorld() { return 'Hello World'; } }
操作ID
操作通常是用来执行资源的特定操作,因此,操作ID通常为动词,如view, update等。
操作ID应仅包含英文小写字母、数字、下划线和中横杠,操作ID中的中横杠用来分隔单词。 例如view, update2, comment-post是真实的操作ID,view?, Update不是操作ID.
可通过两种方式创建操作ID,内联操作和独立操作. An inline action is 内联操作在控制器类中定义为方法;独立操作是继承yii\base\Action或它的子类的类。 内联操作容易创建,在无需重用的情况下优先使用; 独立操作相反,主要用于多个控制器重用,或重构为扩展。
内联操作
内联操作指的是根据我们刚描述的操作方法。
操作方法的名字是根据操作ID遵循如下规则衍生:
注意: 操作方法的名字大小写敏感,如果方法名称为ActionIndex不会认为是操作方法, 所以请求index操作会返回一个异常,也要注意操作方法必须是公有的,私有或者受保护的方法不能定义成内联操作。
因为容易创建,内联操作是最常用的操作,但是如果你计划在不同地方重用相同的操作, 或者你想重新分配一个操作,需要考虑定义它为独立操作。
独立操作
独立操作通过继承yii\base\Action或它的子类来定义。 例如Yii发布的yii\web\ViewAction和yii\web\ErrorAction都是独立操作。
要使用独立操作,需要通过控制器中覆盖yii\base\Controller::actions()方法在action map中申明,如下例所示:
public function actions() { return [ // 用类来申明"error" 操作 'error' => 'yii\web\ErrorAction', // 用配置数组申明 "view" 操作 'view' => [ 'class' => 'yii\web\ViewAction', 'viewPrefix' => '', ], ]; }
如上所示, actions() 方法返回键为操作ID、值为对应操作类名或数组configurations 的数组。 和内联操作不同,独立操作ID可包含任意字符,只要在actions() 方法中申明.
为创建一个独立操作类,需要继承yii\base\Action 或它的子类,并实现公有的名称为run()的方法, run() 方法的角色和操作方法类似,例如:
<?php namespace app\components; use yii\base\Action; class HelloWorldAction extends Action { public function run() { return "Hello World"; } }
操作结果
操作方法或独立操作的run()方法的返回值非常重要,它表示对应操作结果。
返回值可为 响应 对象,作为响应发送给终端用户。
对于yii\web\Application网页应用,返回值可为任意数据, 它赋值给yii\web\Response::data, 最终转换为字符串来展示响应内容。
对于yii\console\Application控制台应用,返回值可为整数, 表示命令行下执行的 yii\console\Response::exitStatus 退出状态。
在上面的例子中,操作结果都为字符串,作为响应数据发送给终端用户,下例显示一个操作通过 返回响应对象(因为yii\web\Controller::redirect()方法返回一个响应对象)可将用户浏览器跳转到新的URL。
public function actionForward()
{ // 用户浏览器跳转到 http://example.com return $this->redirect('http://example.com'); }
操作参数
内联操作的操作方法和独立操作的 run() 方法可以带参数,称为操作参数。 参数值从请求中获取,对于yii\web\Application网页应用, 每个操作参数的值从$_GET中获得,参数名作为键; 对于yii\console\Application控制台应用, 操作参数对应命令行参数。
如下例,操作view (内联操作) 申明了两个参数 $id 和 $version。
namespace app\controllers; use yii\web\Controller; class PostController extends Controller { public function actionView($id, $version = null) { // ... } }
操作参数会被不同的参数填入,如下所示:
http://hostname/index.php?r=post/view&id=123: $id 会填入'123',$version 仍为 null 空因为没有version请求参数;
http://hostname/index.php?r=post/view&id=123&version=2: $id 和 $version 分别填入 '123' 和 '2'`;
http://hostname/index.php?r=post/view: 会抛出yii\web\BadRequestHttpException 异常 因为请求没有提供参数给必须赋值参数$id;
http://hostname/index.php?r=post/view&id[]=123: 会抛出yii\web\BadRequestHttpException 异常 因为$id 参数收到数字值 ['123']而不是字符串.
如果想让操作参数接收数组值,需要指定$id为array,如下所示:
public function actionView(array $id, $version = null) { // ... }
现在如果请求为 http://hostname/index.php?r=post/view&id[]=123, 参数 $id 会使用数组值['123'], 如果请求为http://hostname/index.php?r=post/view&id=123, 参数 $id 会获取相同数组值,因为无类型的'123'会自动转成数组。
上述例子主要描述网页应用的操作参数,对于控制台应用,更多详情请参阅控制台命令。
默认操作
每个控制器都有一个由 yii\base\Controller::defaultAction 属性指定的默认操作, 当路由 只包含控制器ID,会使用所请求的控制器的默认操作。
默认操作默认为 index,如果想修改默认操作,只需简单地在控制器类中覆盖这个属性,如下所示:
namespace app\controllers; use yii\web\Controller; class SiteController extends Controller { public $defaultAction = 'home'; public function actionHome() { return $this->render('home'); } }
控制器动作参数绑定
从版本 1.1.4 开始,Yii 提供了对自动动作参数绑定的支持。就是说,控制器动作可以定义命名的参数,参数的值将由 Yii 自动从 $_GET 填充。
为了详细说明此功能,假设我们需要为 PostController 写一个 create 动作。此动作需要两个参数:
从 $_GET 中提取参数时,我们可以不再下面这种无聊的代码了:
class PostController extends CController { public function actionCreate() { if(isset($_GET['category'])) $category=(int)$_GET['category']; else throw new CHttpException(404,'invalid request'); if(isset($_GET['language'])) $language=$_GET['language']; else $language='en'; // ... fun code starts here ... } }
现在使用动作参数功能,我们可以更轻松的完成任务:
class PostController extends CController { public function actionCreate($category, $language='en') { $category = (int)$category; echo 'Category:'.$category.'/Language:'.$language; // ... fun code starts here ... } }
注意我们在动作方法 actionCreate 中添加了两个参数。这些参数的名字必须和我们想要从 $_GET 中提取的名字一致。当用户没有在请求中指定 $language 参数时,这个参数会使用默认值 en 。由于 $category 没有默认值,如果用户没有在 $_GET 中提供 category 参数,将会自动抛出一个 CHttpException (错误代码 400) 异常。
从版本1.1.5开始,Yii已经支持数组的动作参数。使用方法如下:
class PostController extends CController { public function actionCreate(array $categories) { // Yii will make sure $categories be an array } }
控制器生命周期
处理一个请求时,应用主体 会根据请求路由创建一个控制器,控制器经过以下生命周期来完成请求:
最佳实践
在设计良好的应用中,控制器很精练,包含的操作代码简短; 如果你的控制器很复杂,通常意味着需要重构,转移一些代码到其他类中。
归纳起来,控制器: