国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
Detailed explanation of the Controller controller in the Yii framework of PHP. The yiicontroller
Articles you may be interested in:
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

Jul 12, 2016 am 08:55 AM
php yii

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

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

  // 用配置數(shù)組申明 "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',
]

創(chuàng)建操作

創(chuàng)建操作可簡單地在控制器類中定義所謂的 操作方法 來完成,操作方法必須是以action開頭的公有方法。 操作方法的返回值會作為響應數(shù)據(jù)發(fā)送給終端用戶,如下代碼定義了兩個操作 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

操作通常是用來執(zhí)行資源的特定操作,因此,操作ID通常為動詞,如view, update等。

操作ID應僅包含英文小寫字母、數(shù)字、下劃線和中橫杠,操作ID中的中橫杠用來分隔單詞。 例如view, update2, comment-post是真實的操作ID,view?, Update不是操作ID.

可通過兩種方式創(chuàng)建操作ID,內(nèi)聯(lián)操作和獨立操作. An inline action is 內(nèi)聯(lián)操作在控制器類中定義為方法;獨立操作是繼承yii\base\Action或它的子類的類。 內(nèi)聯(lián)操作容易創(chuàng)建,在無需重用的情況下優(yōu)先使用; 獨立操作相反,主要用于多個控制器重用,或重構為擴展。

內(nèi)聯(lián)操作

內(nèi)聯(lián)操作指的是根據(jù)我們剛描述的操作方法。

操作方法的名字是根據(jù)操作ID遵循如下規(guī)則衍生:

  • 將每個單詞的第一個字母轉(zhuǎn)為大寫;
  • 去掉中橫杠;
  • 增加action前綴.
  • 例如index 轉(zhuǎn)成 actionIndex, hello-world 轉(zhuǎn)成 actionHelloWorld。

注意: 操作方法的名字大小寫敏感,如果方法名稱為ActionIndex不會認為是操作方法, 所以請求index操作會返回一個異常,也要注意操作方法必須是公有的,私有或者受保護的方法不能定義成內(nèi)聯(lián)操作。
因為容易創(chuàng)建,內(nèi)聯(lián)操作是最常用的操作,但是如果你計劃在不同地方重用相同的操作, 或者你想重新分配一個操作,需要考慮定義它為獨立操作。

獨立操作

獨立操作通過繼承yii\base\Action或它的子類來定義。 例如Yii發(fā)布的yii\web\ViewAction和yii\web\ErrorAction都是獨立操作。

要使用獨立操作,需要通過控制器中覆蓋yii\base\Controller::actions()方法在action map中申明,如下例所示:

public function actions()
{
 return [
  // 用類來申明"error" 操作
  'error' => 'yii\web\ErrorAction',

  // 用配置數(shù)組申明 "view" 操作
  'view' => [
   'class' => 'yii\web\ViewAction',
   'viewPrefix' => '',
  ],
 ];
}

如上所示, actions() 方法返回鍵為操作ID、值為對應操作類名或數(shù)組configurations 的數(shù)組。 和內(nèi)聯(lián)操作不同,獨立操作ID可包含任意字符,只要在actions() 方法中申明.

為創(chuàng)建一個獨立操作類,需要繼承yii\base\Action 或它的子類,并實現(xiàn)公有的名稱為run()的方法, run() 方法的角色和操作方法類似,例如:

<&#63;php
namespace app\components;

use yii\base\Action;

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

操作結(jié)果

操作方法或獨立操作的run()方法的返回值非常重要,它表示對應操作結(jié)果。

返回值可為 響應 對象,作為響應發(fā)送給終端用戶。

對于yii\web\Application網(wǎng)頁應用,返回值可為任意數(shù)據(jù), 它賦值給yii\web\Response::data, 最終轉(zhuǎn)換為字符串來展示響應內(nèi)容。
對于yii\console\Application控制臺應用,返回值可為整數(shù), 表示命令行下執(zhí)行的 yii\console\Response::exitStatus 退出狀態(tài)。
在上面的例子中,操作結(jié)果都為字符串,作為響應數(shù)據(jù)發(fā)送給終端用戶,下例顯示一個操作通過 返回響應對象(因為yii\web\Controller::redirect()方法返回一個響應對象)可將用戶瀏覽器跳轉(zhuǎn)到新的URL。

public function actionForward()

{
 // 用戶瀏覽器跳轉(zhuǎn)到 http://example.com
 return $this->redirect('http://example.com');
}

操作參數(shù)

內(nèi)聯(lián)操作的操作方法和獨立操作的 run() 方法可以帶參數(shù),稱為操作參數(shù)。 參數(shù)值從請求中獲取,對于yii\web\Application網(wǎng)頁應用, 每個操作參數(shù)的值從$_GET中獲得,參數(shù)名作為鍵; 對于yii\console\Application控制臺應用, 操作參數(shù)對應命令行參數(shù)。

如下例,操作view (內(nèi)聯(lián)操作) 申明了兩個參數(shù) $id 和 $version。

namespace app\controllers;

use yii\web\Controller;

class PostController extends Controller
{
  public function actionView($id, $version = null)
  {
    // ...
  }
}

操作參數(shù)會被不同的參數(shù)填入,如下所示:

http://hostname/index.php?r=post/view&id=123: $id 會填入'123',$version 仍為 null 空因為沒有version請求參數(shù);
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 異常 因為請求沒有提供參數(shù)給必須賦值參數(shù)$id;
http://hostname/index.php?r=post/view&id[]=123: 會拋出yii\web\BadRequestHttpException 異常 因為$id 參數(shù)收到數(shù)字值 ['123']而不是字符串.
如果想讓操作參數(shù)接收數(shù)組值,需要指定$id為array,如下所示:

public function actionView(array $id, $version = null)
{
 // ...
}

現(xiàn)在如果請求為 http://hostname/index.php?r=post/view&id[]=123, 參數(shù) $id 會使用數(shù)組值['123'], 如果請求為http://hostname/index.php?r=post/view&id=123, 參數(shù) $id 會獲取相同數(shù)組值,因為無類型的'123'會自動轉(zhuǎn)成數(shù)組。

上述例子主要描述網(wǎng)頁應用的操作參數(shù),對于控制臺應用,更多詳情請參閱控制臺命令。

默認操作

每個控制器都有一個由 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');
 }
}

控制器動作參數(shù)綁定
從版本 1.1.4 開始,Yii 提供了對自動動作參數(shù)綁定的支持。就是說,控制器動作可以定義命名的參數(shù),參數(shù)的值將由 Yii 自動從 $_GET 填充。

為了詳細說明此功能,假設我們需要為 PostController 寫一個 create 動作。此動作需要兩個參數(shù):

  • category:一個整數(shù),代表帖子(post)要發(fā)表在的那個分類的ID。
  • language:一個字符串,代表帖子所使用的語言代碼。

從 $_GET 中提取參數(shù)時,我們可以不再下面這種無聊的代碼了:

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

現(xiàn)在使用動作參數(shù)功能,我們可以更輕松的完成任務:

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

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

注意我們在動作方法 actionCreate 中添加了兩個參數(shù)。這些參數(shù)的名字必須和我們想要從 $_GET 中提取的名字一致。當用戶沒有在請求中指定 $language 參數(shù)時,這個參數(shù)會使用默認值 en 。由于 $category 沒有默認值,如果用戶沒有在 $_GET 中提供 category 參數(shù),將會自動拋出一個 CHttpException (錯誤代碼 400) 異常。

從版本1.1.5開始,Yii已經(jīng)支持數(shù)組的動作參數(shù)。使用方法如下:

  class PostController extends CController
  {
    public function actionCreate(array $categories)
    {
      // Yii will make sure $categories be an array
    }
  }

控制器生命周期

處理一個請求時,應用主體 會根據(jù)請求路由創(chuàng)建一個控制器,控制器經(jīng)過以下生命周期來完成請求:

  • 在控制器創(chuàng)建和配置后,yii\base\Controller::init() 方法會被調(diào)用。
  • 控制器根據(jù)請求操作ID創(chuàng)建一個操作對象:
  • 如果操作ID沒有指定,會使用yii\base\Controller::defaultAction默認操作ID;
  • 如果在yii\base\Controller::actions()找到操作ID,會創(chuàng)建一個獨立操作;
  • 如果操作ID對應操作方法,會創(chuàng)建一個內(nèi)聯(lián)操作;
  • 否則會拋出yii\base\InvalidRouteException異常。
  • 控制器按順序調(diào)用應用主體、模塊(如果控制器屬于模塊)、控制器的 beforeAction() 方法;
  • 如果任意一個調(diào)用返回false,后面未調(diào)用的beforeAction()會跳過并且操作執(zhí)行會被取消; action execution will be cancelled.
  • 默認情況下每個 beforeAction() 方法會觸發(fā)一個 beforeAction 事件,在事件中你可以追加事件處理操作;
  • 控制器執(zhí)行操作:
  • 請求數(shù)據(jù)解析和填入到操作參數(shù);
  • 控制器按順序調(diào)用控制器、模塊(如果控制器屬于模塊)、應用主體的 afterAction() 方法;
  • 默認情況下每個 afterAction() 方法會觸發(fā)一個 afterAction 事件,在事件中你可以追加事件處理操作;
  • 應用主體獲取操作結(jié)果并賦值給響應.


最佳實踐

在設計良好的應用中,控制器很精練,包含的操作代碼簡短; 如果你的控制器很復雜,通常意味著需要重構,轉(zhuǎn)移一些代碼到其他類中。

歸納起來,控制器:

  • 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. ...
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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

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.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use php exit function? How to use php exit function? Jul 03, 2025 am 02:15 AM

exit() is a function in PHP that is used to terminate script execution immediately. Common uses include: 1. Terminate the script in advance when an exception is detected, such as the file does not exist or verification fails; 2. Output intermediate results during debugging and stop execution; 3. Call exit() after redirecting in conjunction with header() to prevent subsequent code execution; In addition, exit() can accept string parameters as output content or integers as status code, and its alias is die().

Applying Semantic Structure with article, section, and aside in HTML Applying Semantic Structure with article, section, and aside in HTML Jul 05, 2025 am 02:03 AM

The rational use of semantic tags in HTML can improve page structure clarity, accessibility and SEO effects. 1. Used for independent content blocks, such as blog posts or comments, it must be self-contained; 2. Used for classification related content, usually including titles, and is suitable for different modules of the page; 3. Used for auxiliary information related to the main content but not core, such as sidebar recommendations or author profiles. In actual development, labels should be combined and other, avoid excessive nesting, keep the structure simple, and verify the rationality of the structure through developer tools.

The requested operation requires elevation Windows The requested operation requires elevation Windows Jul 04, 2025 am 02:58 AM

When you encounter the prompt "This operation requires escalation of permissions", it means that you need administrator permissions to continue. Solutions include: 1. Right-click the "Run as Administrator" program or set the shortcut to always run as an administrator; 2. Check whether the current account is an administrator account, if not, switch or request administrator assistance; 3. Use administrator permissions to open a command prompt or PowerShell to execute relevant commands; 4. Bypass the restrictions by obtaining file ownership or modifying the registry when necessary, but such operations need to be cautious and fully understand the risks. Confirm permission identity and try the above methods usually solve the problem.

How to handle File Uploads securely in PHP? How to handle File Uploads securely in PHP? Jul 08, 2025 am 02:37 AM

To safely handle PHP file uploads, you need to verify the source and type, control the file name and path, set server restrictions, and process media files twice. 1. Verify the upload source to prevent CSRF through token and detect the real MIME type through finfo_file using whitelist control; 2. Rename the file to a random string and determine the extension to store it in a non-Web directory according to the detection type; 3. PHP configuration limits the upload size and temporary directory Nginx/Apache prohibits access to the upload directory; 4. The GD library resaves the pictures to clear potential malicious data.

How Do You Pass Variables by Value vs. by Reference in PHP? How Do You Pass Variables by Value vs. by Reference in PHP? Jul 08, 2025 am 02:42 AM

InPHP,variablesarepassedbyvaluebydefault,meaningfunctionsorassignmentsreceiveacopyofthedata,whilepassingbyreferenceallowsmodificationstoaffecttheoriginalvariable.1.Whenpassingbyvalue,changestothecopydonotimpacttheoriginal,asshownwhenassigning$b=$aorp

PHP header location ajax call not working PHP header location ajax call not working Jul 10, 2025 pm 01:46 PM

The reason why header('Location:...') in AJAX request is invalid is that the browser will not automatically perform page redirects. Because in the AJAX request, the 302 status code and Location header information returned by the server will be processed as response data, rather than triggering the jump behavior. Solutions are: 1. Return JSON data in PHP and include a jump URL; 2. Check the redirect field in the front-end AJAX callback and jump manually with window.location.href; 3. Ensure that the PHP output is only JSON to avoid parsing failure; 4. To deal with cross-domain problems, you need to set appropriate CORS headers; 5. To prevent cache interference, you can add a timestamp or set cache:f

How Do Generators Work in PHP? How Do Generators Work in PHP? Jul 11, 2025 am 03:12 AM

AgeneratorinPHPisamemory-efficientwaytoiterateoverlargedatasetsbyyieldingvaluesoneatatimeinsteadofreturningthemallatonce.1.Generatorsusetheyieldkeywordtoproducevaluesondemand,reducingmemoryusage.2.Theyareusefulforhandlingbigloops,readinglargefiles,or

PHP find the position of the last occurrence of a substring PHP find the position of the last occurrence of a substring Jul 09, 2025 am 02:49 AM

The most direct way to find the last occurrence of a substring in PHP is to use the strrpos() function. 1. Use strrpos() function to directly obtain the index of the last occurrence of the substring in the main string. If it is not found, it returns false. The syntax is strrpos($haystack,$needle,$offset=0). 2. If you need to ignore case, you can use the strripos() function to implement case-insensitive search. 3. For multi-byte characters such as Chinese, the mb_strrpos() function in the mbstring extension should be used to ensure that the character position is returned instead of the byte position. 4. Note that strrpos() returns f

See all articles