search
HomeBackend DevelopmentPHP TutorialFor the analysis of Controller controller in PHP's Yii framework

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
PHP: An Introduction to the Server-Side Scripting LanguagePHP: An Introduction to the Server-Side Scripting LanguageApr 16, 2025 am 12:18 AM

PHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.

PHP and the Web: Exploring its Long-Term ImpactPHP and the Web: Exploring its Long-Term ImpactApr 16, 2025 am 12:17 AM

PHP has shaped the network over the past few decades and will continue to play an important role in web development. 1) PHP originated in 1994 and has become the first choice for developers due to its ease of use and seamless integration with MySQL. 2) Its core functions include generating dynamic content and integrating with the database, allowing the website to be updated in real time and displayed in personalized manner. 3) The wide application and ecosystem of PHP have driven its long-term impact, but it also faces version updates and security challenges. 4) Performance improvements in recent years, such as the release of PHP7, enable it to compete with modern languages. 5) In the future, PHP needs to deal with new challenges such as containerization and microservices, but its flexibility and active community make it adaptable.

Why Use PHP? Advantages and Benefits ExplainedWhy Use PHP? Advantages and Benefits ExplainedApr 16, 2025 am 12:16 AM

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

Debunking the Myths: Is PHP Really a Dead Language?Debunking the Myths: Is PHP Really a Dead Language?Apr 16, 2025 am 12:15 AM

PHP is not dead. 1) The PHP community actively solves performance and security issues, and PHP7.x improves performance. 2) PHP is suitable for modern web development and is widely used in large websites. 3) PHP is easy to learn and the server performs well, but the type system is not as strict as static languages. 4) PHP is still important in the fields of content management and e-commerce, and the ecosystem continues to evolve. 5) Optimize performance through OPcache and APC, and use OOP and design patterns to improve code quality.

The PHP vs. Python Debate: Which is Better?The PHP vs. Python Debate: Which is Better?Apr 16, 2025 am 12:03 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on the project requirements. 1) PHP is suitable for web development, easy to learn, rich community resources, but the syntax is not modern enough, and performance and security need to be paid attention to. 2) Python is suitable for data science and machine learning, with concise syntax and easy to learn, but there are bottlenecks in execution speed and memory management.

PHP's Purpose: Building Dynamic WebsitesPHP's Purpose: Building Dynamic WebsitesApr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP: Handling Databases and Server-Side LogicPHP: Handling Databases and Server-Side LogicApr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

How do you prevent SQL Injection in PHP? (Prepared statements, PDO)How do you prevent SQL Injection in PHP? (Prepared statements, PDO)Apr 15, 2025 am 12:15 AM

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft