


Detailed explanation of the Controller controller in PHP's Yii framework_php skills
The 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:
- 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 { }
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, ], ], ]
默认控制器
每个应用有一个由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('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 动作。此动作需要两个参数:
- 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 ... } }
现在使用动作参数功能,我们可以更轻松的完成任务:
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 } }
Controller life cycle
When processing a request, the application body will create a controller based on the request route. The controller goes through the following life cycle to complete the request:
- After the controller is created and configured, the yiibaseController::init() method will be called.
- The controller creates an operation object based on the request operation ID:
- If the operation ID is not specified, the default operation ID of yiibaseController::defaultAction will be used;
- If the operation ID is found in yiibaseController::actions(), an independent operation will be created;
- If the operation ID corresponds to the operation method, an inline operation will be created;
- Otherwise, a yiibaseInvalidRouteException will be thrown.
- The controller calls the application body, module (if the controller belongs to a module), and the controller's beforeAction() method in sequence;
- If any call returns false, the subsequent uncalled beforeAction() will be skipped and the operation execution will be canceled; action execution will be canceled.
- By default, each beforeAction() method will trigger a beforeAction event, in which you can add event processing operations;
- Controller performs action:
- Request data parsing and filling in operation parameters;
- The controller calls the afterAction() method of the controller, module (if the controller belongs to a module), and the application body in order;
- By default, each afterAction() method will trigger an afterAction event, in which you can add event processing operations;
- The application body obtains the operation result and assigns it to the response.
Best Practices
In a well-designed application, the controller is concise and contains short operation code; if your controller is complex, it usually means that you need to refactor and transfer some code to other classes.
To sum it up, controller:
- 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.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.
