Home  >  Article  >  Backend Development  >  For the analysis of Controller controller in PHP's Yii framework

For the analysis of Controller controller in PHP's Yii framework

不言
不言Original
2018-06-19 14:26:341463browse

This article mainly introduces the Controller controller in the Yii framework of PHP. As an MVC framework, the use of the controller part of Yii is naturally the top priority. Friends in need can refer to

Control The controller is part of the MVC pattern. It is an object that inherits the yii\base\Controller 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

The 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 operation views 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 based on the requested 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 the actionCreate() method), the code is similar. First fill in the request data into the model, and then save the model. If both are successful, it will jump to the newly created model with the ID view operation, otherwise the create view that provides user input is displayed.

Routing

End users find operations through so-called routes, which are strings containing the following parts:

  • Model ID: only exists when the controller belongs to a non-application module;

  • Controller ID: uniquely identifies the controller in the same application (or the same module if it is a controller under the module) String;

  • Operation ID: A string that uniquely identifies the operation under the same controller.

Routing 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 a controller

In the yii\web\Application web application, the controller should inherit yii\web\Controller or its subclass. Similarly, in the yii\console\Application console application, the controller inherits yii\console\Controller or its subclasses. The following code defines a site controller:

namespace app\controllers;

use yii\web\Controller;

class SiteController extends Controller
{
}

Controller ID

Normally, the controller is used to process 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, article?, PostComment, admin\post are not controls. Device ID.

The controller ID can include the subdirectory prefix, for example, admin/article represents the article controller in the admin subdirectory under the yii\base\Application::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:

Separate each word with a forward slash The first letter is converted 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 middle horizontal slash and replace the forward slash with a backslash;
Add Controller suffix;
Add the yii\base\Application::controllerNamespace controller namespace in front.
The following are some examples, assuming that the yii\base\Application::controllerNamespace controller namespace is app\controllers:

  • article corresponds to app\controllers\ArticleController;

  • post-comment corresponds to app\controllers\PostCommentController;

  • admin/post-comment corresponds to app\controllers\admin\PostCommentController;

  • adminPanels/post-comment corresponds to app\controllers\adminPanels\PostCommentController.

The controller class must be automatically loaded, so in the above example, the controller article class should be defined in the file with the alias @app/controllers/ArticleController.php, and the controller admin/post2-comment should be in @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 yii\base\Application::controllerNamespace controller namespace, if you do not want to use the module This method is useful for classifying controllers.
Controller deployment

You can configure yii\base\Application::controllerMap to force the above controller ID and class name to correspond. It is usually used when a third party cannot control the class. on the named controller.

Configuration The application configuration in Application Configuration is as follows:

[
 'controllerMap' => [
  // 用类名申明 "account" 控制器
  'account' => 'app\controllers\UserController',

  // 用配置数组申明 "article" 控制器
  'article' => [
   'class' => 'app\controllers\PostController',
   'enableCsrfValidation' => false,
  ],
 ],
]

Default Controller

每个应用有一个由yii\base\Application::defaultRoute属性指定的默认控制器; 当请求没有指定 路由,该属性值作为路由使用。 对于yii\web\Application网页应用,它的值为 'site', 对于 yii\console\Application控制台应用,它的值为 help, 所以URL为http://hostname/index.php 表示由 site 控制器来处理。

可以在 应用配置 中修改默认控制器,如下所示:

[
 '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遵循如下规则衍生:

  • 将每个单词的第一个字母转为大写;

  • 去掉中横杠;

  • 增加action前缀.

  • 例如index 转成 actionIndex, hello-world 转成 actionHelloWorld。

注意: 操作方法的名字大小写敏感,如果方法名称为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(&#39;http://example.com&#39;);
}

操作参数

内联操作的操作方法和独立操作的 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 = &#39;home&#39;;

 public function actionHome()
 {
  return $this->render(&#39;home&#39;);
 }
}

控制器动作参数绑定 
从版本 1.1.4 开始,Yii 提供了对自动动作参数绑定的支持。就是说,控制器动作可以定义命名的参数,参数的值将由 Yii 自动从 $_GET 填充。

       为了详细说明此功能,假设我们需要为 PostController 写一个 create 动作。此动作需要两个参数:

  •        category:一个整数,代表帖子(post)要发表在的那个分类的ID。

  •        language:一个字符串,代表帖子所使用的语言代码。

       从 $_GET 中提取参数时,我们可以不再下面这种无聊的代码了:

 class PostController extends CController
  {
    public function actionCreate()
    {
      if(isset($_GET[&#39;category&#39;]))
       $category=(int)$_GET[&#39;category&#39;];
      else
       throw new CHttpException(404,&#39;invalid request&#39;);
 
      if(isset($_GET[&#39;language&#39;]))
       $language=$_GET[&#39;language&#39;];
      else
       $language=&#39;en&#39;;
 
      // ... fun code starts here ...
    }
  }

       现在使用动作参数功能,我们可以更轻松的完成任务:

  class PostController extends CController
  {
    public function actionCreate($category, $language=&#39;en&#39;)
    {
      $category = (int)$category;

      echo &#39;Category:&#39;.$category.&#39;/Language:&#39;.$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
    }
  }

控制器生命周期

处理一个请求时,应用主体 会根据请求路由创建一个控制器,控制器经过以下生命周期来完成请求:

  • 在控制器创建和配置后,yii\base\Controller::init() 方法会被调用。

  • 控制器根据请求操作ID创建一个操作对象:

  • 如果操作ID没有指定,会使用yii\base\Controller::defaultAction默认操作ID;

  • 如果在yii\base\Controller::actions()找到操作ID,会创建一个独立操作;

  • 如果操作ID对应操作方法,会创建一个内联操作;

  • 否则会抛出yii\base\InvalidRouteException异常。

  • 控制器按顺序调用应用主体、模块(如果控制器属于模块)、控制器的 beforeAction() 方法;

  • 如果任意一个调用返回false,后面未调用的beforeAction()会跳过并且操作执行会被取消; action execution will be cancelled.

  • 默认情况下每个 beforeAction() 方法会触发一个 beforeAction 事件,在事件中你可以追加事件处理操作;

  • 控制器执行操作:

  • 请求数据解析和填入到操作参数;

  • 控制器按顺序调用控制器、模块(如果控制器属于模块)、应用主体的 afterAction() 方法;

  • 默认情况下每个 afterAction() 方法会触发一个 afterAction 事件,在事件中你可以追加事件处理操作;

  • 应用主体获取操作结果并赋值给响应.

最佳实践

在设计良好的应用中,控制器很精练,包含的操作代码简短; 如果你的控制器很复杂,通常意味着需要重构,转移一些代码到其他类中。

To sum up, the controller:

  • can access the request data;

  • can call the model's methods and other service components based on the request data. ;

  • Responses can be constructed using views;

  • Request data that should be processed by the model should not be processed;

  • You should avoid embedding HTML or other display code. These codes are best handled in the view.

The above is the entire content of this article. I hope it will be helpful to everyone's learning. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

About the usage of Yii’s CDbCriteria query conditions

About the PHP custom serialization interface Serializable Usage analysis

About the usage of Zend Framework action controller

##

The above is the detailed content of For the analysis of Controller controller in PHP's Yii framework. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn