Home > Backend Development > PHP Tutorial > Detailed explanation of the Controller controller in PHP's Yii framework, yiicontroller_PHP tutorial

Detailed explanation of the Controller controller in PHP's Yii framework, yiicontroller_PHP tutorial

WBOY
Release: 2016-07-12 08:55:14
Original
904 people have browsed it

Detailed explanation of the Controller controller in the Yii framework of PHP. The yiicontroller

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,
   ]);
  }
 }
}

Copy after login

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:

  • Model ID: Only exists in modules where the controller belongs to non-applications;
  • Controller ID: A string that uniquely identifies the controller in the same application (or the same module if it is a controller under the module);
  • Operation ID: A string that uniquely identifies the operation under the same controller.

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
{
}

Copy after login

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:

  • article corresponds to appcontrollersArticleController;
  • post-comment corresponds to appcontrollersPostCommentController;
  • admin/post-comment corresponds to appcontrollersadminPostCommentController;
  • adminPanels/post-comment corresponds to appcontrollersadminPanelsPostCommentController.

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,
  ],
 ],
]

Copy after login

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',
]
Copy after login

创建操作

创建操作可简单地在控制器类中定义所谓的 操作方法 来完成,操作方法必须是以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';
 }
}

Copy after login

操作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' => '',
  ],
 ];
}

Copy after login

如上所示, actions() 方法返回键为操作ID、值为对应操作类名或数组configurations 的数组。 和内联操作不同,独立操作ID可包含任意字符,只要在actions() 方法中申明.

为创建一个独立操作类,需要继承yii\base\Action 或它的子类,并实现公有的名称为run()的方法, run() 方法的角色和操作方法类似,例如:

<&#63;php
namespace app\components;

use yii\base\Action;

class HelloWorldAction extends Action
{
 public function run()
 {
  return "Hello World";
 }
}

Copy after login

操作结果

操作方法或独立操作的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');
}
Copy after login

操作参数

内联操作的操作方法和独立操作的 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)
  {
    // ...
  }
}

Copy after login

操作参数会被不同的参数填入,如下所示:

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)
{
 // ...
}
Copy after login

现在如果请求为 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');
 }
}

Copy after login

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

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

  • category:一个整数,代表帖子(post)要发表在的那个分类的ID。
  • language:一个字符串,代表帖子所使用的语言代码。

从 $_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 ...
    }
  }
Copy after login

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

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

      echo 'Category:'.$category.'/Language:'.$language;
 
      // ... fun code starts here ...
    }
  }

Copy after login

注意我们在动作方法 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
    }
  }

Copy after login

控制器生命周期

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

  • 在控制器创建和配置后,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 事件,在事件中你可以追加事件处理操作;
  • 应用主体获取操作结果并赋值给响应.


最佳实践

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

归纳起来,控制器:

  • Accessible request data;
  • Model methods and other service components can be called based on request data;
  • Views can be used to construct responses;
  • Request data that should be processed by the model should not be processed;
  • Embedded HTML or other presentation code should be avoided and is best handled within the view.

Articles you may be interested in:

  • Detailed explanation of the use of the front-end resource package that comes with PHP's Yii framework
  • Introduction to some advanced usage of caching in PHP's Yii framework
  • In-depth analysis of the caching function in PHP's Yii framework
  • Advanced use of View in PHP's Yii framework
  • Creating and rendering views in PHP's Yii framework Detailed explanation of the method
  • Study tutorial on Model model in PHP’s Yii framework
  • Method to remove the behavior bound to a component in PHP’s Yii framework
  • In PHP’s Yii framework Explanation of behavior definition and binding methods
  • In-depth explanation of properties (Properties) in PHP's Yii framework
  • Detailed explanation of the installation and use of extensions in PHP's Yii framework

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1117075.htmlTechArticleDetailed explanation of the Controller controller in PHP's Yii framework. The yiicontroller controller is part of the MVC pattern and inherits yiibaseController An object of the class responsible for processing requests and generating responses. ...
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template