


Detailed explanation of Yii2 create controller (createController) method_php example
本文实例讲述了Yii2创建控制器(createController)方法。分享给大家供大家参考,具体如下:
yii中创建控制器的是在application中的request通过UrlManager解析得出路由信息的,然后再由yii\base\Module中的
public function runAction($route, $params = [])
方法来创建控制器,最后由控制器再执行相应的动作。
首先得明确,Yii中的路由分三种情况:
第一种是带有模块的(module id/controller id/action id),
第二种是带有命名空间(子目录)的(sub dir)/controller id/action id)
第三种是只有控制器和动作的(controller id/action id)
这三个有优先顺序,所以在创建控制器的时候,也是先查看是否是模块类型的路由,如果是,则获取这个模块,再由这个模块来创建控制器
接着再判断是否是第二种带有命名空间的。
public function createController($route) { //如果路由为空,则使用默认的路由 if ($route === '') { $route = $this->defaultRoute; } // double slashes or leading/ending slashes may cause substr problem //去掉首尾的反斜杠(“/”),如果路由中包含有“//”,则返回false创建失败。 $route = trim($route, '/'); if (strpos($route, '//') !== false) { return false; } /* * 路由分三种情况, * 一种是带模块id的(module id/controller id/action id), * 一种是有命名空间(子目录)的(sub dir)/controller id/action id) * 一种是只有控制器和动作的(controller id/action id) * 所以在这里要根据第一个“/”分隔成两部分,$id和$route信息, */ if (strpos($route, '/') !== false) { list ($id, $route) = explode('/', $route, 2); } else { $id = $route; $route = ''; } // module and controller map take precedence /* * 查看这个id是否是模块,如果是模块,则再用这个模块来创建控制器。 * 所以,在如果一个控制器的名称和模块名称重复的话会优先创建模块里面的控制器。 * * 如果有url: http://www.yii2.com/index.php?r=test/index * 本来是打算访问application中的控制器里面的test控制器,执行index动作的。 * * 然而如果有个模块的名字为test,里面有个IndexController * * 根据上面会生成$id=test,$route=index * * 由于在下面查找存在这个模块,所以会执行这个test模块下面的index控制器, * 而不会执行application里面的test控制器的index动作 */ $module = $this->getModule($id); if ($module !== null) { return $module->createController($route); } //如果在controllerMap数组中指定了控制器映射,会优先根据这个里面的映射来创建控制器 if (isset($this->controllerMap[$id])) { $controller = Yii::createObject($this->controllerMap[$id], [$id, $this]); return [$controller, $route]; } /* * 如果这个时候$route中还有“/”,也就是说原来的路由为home/index/aa * $id:home(不是模块) * $route:index/aa * 由于经过上面得知home不为模块,所以这个为命名空间(子目录), * * 再经过下面处理后为 * $id:home/index 命名空间(子目录)home下面的index控制器 * $route:aaa * */ if (($pos = strrpos($route, '/')) !== false) { $id .= '/' . substr($route, 0, $pos); $route = substr($route, $pos + 1); } /* * $id:home/index * $route:aaa */ $controller = $this->createControllerByID($id); if ($controller === null && $route !== '') { //如果创建失败,再加上route作为id再次创建 $controller = $this->createControllerByID($id . '/' . $route); $route = ''; } return $controller === null ? false : [$controller, $route]; }
在这个函数中$id就有两种情况,一种是前面带有命名空间的,一种是直接就一个控制器ID的。
public function createControllerByID($id) { if (!preg_match('%^[a-z0-9\\-_/]+$%', $id)) { return null; } /* * 如果$id中有“/”,则前面的为目录,后面的为类 * */ $pos = strrpos($id, '/'); if ($pos === false) { $prefix = ''; $className = $id; } else { $prefix = substr($id, 0, $pos + 1); $className = substr($id, $pos + 1); } //生成控制器的类IndexController $className = str_replace(' ', '', ucwords(str_replace('-', ' ', $className))) . 'Controller'; //如果有前缀(也就是有目录、命名空间),则在类前面加上命名空间 $className = ltrim($this->controllerNamespace . '\\' . str_replace('/', '\\', $prefix) . $className, '\\'); //如果类不存在,或者类名称包含“-”,则出错, if (strpos($className, '-') !== false || !class_exists($className)) { return null; } //下面就是创建类了 if (is_subclass_of($className, 'yii\base\Controller')) { return new $className($id, $this); } elseif (YII_DEBUG) { throw new InvalidConfigException("Controller class must extend from \\yii\\base\\Controller."); } else { return null; } }
这个过程就结束了,然后再由创建出来的控制器执行它里面的动作
public function runAction($route, $params = []) { $parts = $this->createController($route); if (is_array($parts)) { /** @var Controller $controller */ list($controller, $actionID) = $parts; $oldController = Yii::$app->controller; Yii::$app->controller = $controller; //控制器执行相应的动作 $result = $controller->runAction($actionID, $params); Yii::$app->controller = $oldController; return $result; } else { $id = $this->getUniqueId(); throw new InvalidRouteException('Unable to resolve the request "' . ($id === '' ? $route : $id . '/' . $route) . '".'); } }
更多关于Yii相关内容感兴趣的读者可查看本站专题:《Yii框架入门及常用技巧总结》、《php优秀开发框架总结》、《smarty模板入门基础教程》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》
希望本文所述对大家基于Yii框架的PHP程序设计有所帮助。

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











Since Windows has become the gaming platform of choice, it's even more important to identify its gaming-oriented features. One of them is the ability to calibrate an Xbox One controller on Windows 11. With built-in manual calibration, you can get rid of drift, random movement, or performance issues and effectively align the X, Y, and Z axes. If the available options don't work, you can always use a third-party Xbox One controller calibration tool. Let’s find out! How do I calibrate my Xbox controller on Windows 11? Before proceeding, make sure you connect your controller to your computer and update your Xbox One controller's drivers. While you're at it, also install any available firmware updates. 1. Use Wind

How to Personalize Calls on iPhone Apple’s iOS 17 introduces a new feature called Contact Posters that allows you to personalize the look of your call screen on your iPhone. This feature allows you to design a poster using selected photos, colors, fonts, and Memoji as contact cards. So when you make a call, your custom image will appear on the recipient's iPhone exactly as you envisioned. You can choose to share your unique contact poster with all your saved contacts, or choose who can see it. Likewise, during a call exchange, you will also see other people's contact posters. Additionally, Apple lets you set specific contact photos for individual contacts, making calls from those contacts

Constants and variables are used to store data values in programming. A variable usually refers to a value that can change over time. A constant is a type of variable whose value cannot be changed during program execution. There are only six built-in constants available in Python, they are False, True, None, NotImplemented, Ellipsis(...) and __debug__. Apart from these constants, Python does not have any built-in data types to store constant values. Example An example of a constant is demonstrated below - False=100 outputs SyntaxError:cannotassigntoFalseFalse is a built-in constant in Python that is used to store boolean values

Title: Realme Phone Beginner’s Guide: How to Create Folders on Realme Phone? In today's society, mobile phones have become an indispensable tool in people's lives. As a popular smartphone brand, Realme Phone is loved by users for its simple and practical operating system. In the process of using Realme phones, many people may encounter situations where they need to organize files and applications on their phones, and creating folders is an effective way. This article will introduce how to create folders on Realme phones to help users better manage their phone content. No.

Many friends expressed that they want to know how to create a family in Gree+ software. Here is the operation method for you. Friends who want to know more, come and take a look with me. First, open the Gree+ software on your mobile phone and log in. Then, in the options bar at the bottom of the page, click the "My" option on the far right to enter the personal account page. 2. After coming to my page, there is a "Create Family" option under "Family". After finding it, click on it to enter. 3. Next jump to the page to create a family, enter the family name to be set in the input box according to the prompts, and click the "Save" button in the upper right corner after entering it. 4. Finally, a "save successfully" prompt will pop up at the bottom of the page, indicating that the family has been successfully created.

This article will interest you if you are interested in using GIMP for pixel art creation on Windows. GIMP is a well-known graphics editing software that is not only free and open source, but also helps users create beautiful images and designs easily. In addition to being suitable for beginners and professional designers alike, GIMP can also be used to create pixel art, a form of digital art that utilizes pixels as the only building blocks for drawing and creating. How to Create Pixel Art in GIMP Here are the main steps to create pixel pictures using GIMP on a Windows PC: Download and install GIMP, then launch the application. Create a new image. Resize width and height. Select the pencil tool. Set the brush type to pixels. set up

How to use Highcharts to create a Gantt chart requires specific code examples. Introduction: The Gantt chart is a chart form commonly used to display project progress and time management. It can visually display the start time, end time and progress of the task. Highcharts is a powerful JavaScript chart library that provides rich chart types and flexible configuration options. This article will introduce how to use Highcharts to create a Gantt chart and give specific code examples. 1. Highchart

How to create a verification code image using PHP? CAPTCHA is a commonly used method to verify whether the user is a human and not a machine. On websites, we often see verification code images, which require users to enter random characters or numbers displayed on the image to complete operations such as login, registration, and commenting. This article will introduce how to use PHP to create a verification code image and provide specific code examples. 1. PHPGD library To create a verification code image, we need to use PHP's GD library. The GD library is an extension for processing images.
