search
HomeBackend DevelopmentPHP Tutorialyii2 source code study notes (11), yii2 source code study notes_PHP tutorial

yii2 source code study notes (11), yii2 source code study notes

Controller controller class is the base class of all controllers and is used to call models and layouts.

<span>  1</span> <?<span>php
</span><span>  2</span> <span>/*</span><span>*
</span><span>  3</span> <span> * @link </span><span>http://www.yiiframework.com/</span>
<span>  4</span> <span> * @copyright Copyright (c) 2008 Yii Software LLC
</span><span>  5</span> <span> * @license </span><span>http://www.yiiframework.com/license/</span>
<span>  6</span>  <span>*/</span>
<span>  7</span> 
<span>  8</span> <span>namespace</span> yii\<span>base</span><span>;
</span><span>  9</span> 
<span> 10</span> <span>use Yii;
</span><span> 11</span> 
<span> 12</span> <span>/*</span><span>*
</span><span> 13</span> <span> * Controller is the base class for classes containing controller logic.
</span><span> 14</span> <span> *  控制器,是所用控制器类的基类
</span><span> 15</span> <span> * @property Module[] $modules All ancestor modules that this controller is located within. This property is
</span><span> 16</span> <span> * read-only.只读属性  当前控制器的所有模块
</span><span> 17</span> <span> * @property string $route The route (module ID, controller ID and action ID) of the current request. This
</span><span> 18</span> <span> * property is read-only.当前请求的路径  只读属性 可以获取到请求的路径
</span><span> 19</span> <span> * @property string $uniqueId The controller ID that is prefixed with the module ID (if any). This property is
</span><span> 20</span> <span> * read-only.为前缀的controller ID  唯一标识
</span><span> 21</span> <span> * @property View|\yii\web\View $view The view object that can be used to render views or view files.
</span><span> 22</span> <span> * 视图用来传递视图或视图文件.
</span><span> 23</span> <span> * @property string $viewPath The directory containing the view files for this controller. This property is
</span><span> 24</span> <span> * read-only. 包含当前控制器的视图目录
</span><span> 25</span> <span> *
</span><span> 26</span> <span> * @author Qiang Xue <qiang.xue@gmail.com>
</span><span> 27</span> <span> * @since 2.0
</span><span> 28</span>  <span>*/</span>
<span> 29</span> <span>class</span><span> Controller extends Component implements ViewContextInterface
</span><span> 30</span> <span>{
</span><span> 31</span>     <span>/*</span><span>*
</span><span> 32</span> <span>     * @event ActionEvent an event raised right before executing a controller action.
</span><span> 33</span> <span>     * ActionEvent事件提出正确的执行器动作之前执行。
</span><span> 34</span> <span>     * You may set [[ActionEvent::isValid]] to be false to cancel the action execution.
</span><span> 35</span> <span>     * 如果对事件的isValid属性设置为false,将取消action的执行
</span><span> 36</span>      <span>*/</span>
<span> 37</span>     <span>const</span> EVENT_BEFORE_ACTION = <span>'</span><span>beforeAction</span><span>'</span><span>;
</span><span> 38</span>     <span>/*</span><span>*
</span><span> 39</span> <span>     * @event ActionEvent an event raised right after executing a controller action.
</span><span> 40</span> <span>     * 在执行controller操作后触发的事件
</span><span> 41</span>      <span>*/</span>
<span> 42</span>     <span>const</span> EVENT_AFTER_ACTION = <span>'</span><span>afterAction</span><span>'</span><span>;
</span><span> 43</span> 
<span> 44</span>     <span>/*</span><span>*
</span><span> 45</span> <span>     * @var string the ID of this controller.
</span><span> 46</span> <span>     * 控制器id
</span><span> 47</span>      <span>*/</span>
<span> 48</span>     <span>public</span><span> $id;
</span><span> 49</span>     <span>/*</span><span>*
</span><span> 50</span> <span>     * @var Module $module the module that this controller belongs to.
</span><span> 51</span> <span>     * 所属模块
</span><span> 52</span>      <span>*/</span>
<span> 53</span>     <span>public</span><span> $module;
</span><span> 54</span>     <span>/*</span><span>*
</span><span> 55</span> <span>     * @var string the ID of the action that is used when the action ID is not specified
</span><span> 56</span> <span>     * in the request. Defaults to 'index'.控制器中默认动作,默认为index
</span><span> 57</span>      <span>*/</span>
<span> 58</span>     <span>public</span> $defaultAction = <span>'</span><span>index</span><span>'</span><span>;
</span><span> 59</span>     <span>/*</span><span>*
</span><span> 60</span> <span>     * @var string|boolean the name of the layout to be applied to this controller's views.
</span><span> 61</span> <span>     * 布局的名称 应用到该控制器的视图。
</span><span> 62</span> <span>     * This property mainly affects the behavior of [[render()]].此属性主要影响[[render()]]行为
</span><span> 63</span> <span>     * Defaults to null, meaning the actual layout value should inherit that from [[module]]'s layout value.
</span><span> 64</span> <span>     * If false, no layout will be applied. 
</span><span> 65</span> <span>     * 如果设置为false,则不使用布局文件
</span><span> 66</span>      <span>*/</span>
<span> 67</span>     <span>public</span><span> $layout;
</span><span> 68</span>     <span>/*</span><span>*
</span><span> 69</span> <span>     * @var Action the action that is currently being executed. This property will be set
</span><span> 70</span> <span>     * by [[run()]] when it is called by [[Application]] to run an action.
</span><span> 71</span> <span>     * 当前执行的操作,可在事件中根据这个action来执行不同的操作
</span><span> 72</span>      <span>*/</span>
<span> 73</span>     <span>public</span><span> $action;
</span><span> 74</span> 
<span> 75</span>     <span>/*</span><span>*
</span><span> 76</span> <span>     * @var View the view object that can be used to render views or view files.
</span><span> 77</span> <span>     * 视图对象,用来定义输出的视图文件
</span><span> 78</span>      <span>*/</span>
<span> 79</span>     <span>private</span><span> $_view;
</span><span> 80</span> 
<span> 81</span> 
<span> 82</span>     <span>/*</span><span>*
</span><span> 83</span> <span>     * @param string $id the ID of this controller.控制器的ID
</span><span> 84</span> <span>     * @param Module $module the module that this controller belongs to.控制器的模块
</span><span> 85</span> <span>     * @param array $config name-value pairs that will be used to initialize the object properties.
</span><span> 86</span> <span>     * 初始化对像时的配置文件
</span><span> 87</span>      <span>*/</span>
<span> 88</span>     <span>public</span> function __construct($id, $module, $config =<span> [])
</span><span> 89</span> <span>    {
</span><span> 90</span>         <span>//</span><span>初始化控制器id,模块,根据配置文件初始化控制器对象</span>
<span> 91</span>         $<span>this</span>->id =<span> $id;
</span><span> 92</span>         $<span>this</span>->module =<span> $module;
</span><span> 93</span> <span>        parent::__construct($config);
</span><span> 94</span> <span>    }
</span><span> 95</span> 
<span> 96</span>     <span>/*</span><span>*
</span><span> 97</span> <span>     * Declares external actions for the controller.定义action声明控制器的外部操作
</span><span> 98</span> <span>     * This method is meant to be overwritten to declare external actions for the controller.
</span><span> 99</span> <span>     * It should return an array, with array keys being action IDs, and array values the corresponding
</span><span>100</span> <span>     * action class names or action configuration arrays. For example,
</span><span>101</span> <span>     * 这个方法指定独立的action,返回格式为数组,name为action的id,value为action类的实现,
</span><span>102</span> <span>     * ~~~
</span><span>103</span> <span>     * return [
</span><span>104</span> <span>     *     'action1' => 'app\components\Action1',
</span><span>105</span> <span>     *     'action2' => [
</span><span>106</span> <span>     *         'class' => 'app\components\Action2',
</span><span>107</span> <span>     *         'property1' => 'value1',
</span><span>108</span> <span>     *         'property2' => 'value2',
</span><span>109</span> <span>     *     ],
</span><span>110</span> <span>     * ];
</span><span>111</span> <span>     * ~~~
</span><span>112</span> <span>     *
</span><span>113</span> <span>     * [[\Yii::createObject()]] will be used later to create the requested action
</span><span>114</span> <span>     * using the configuration provided here.
</span><span>115</span> <span>     * 使用此处提供的配置来创建请求的操作。
</span><span>116</span>      <span>*/</span>
<span>117</span>     <span>public</span><span> function actions()
</span><span>118</span> <span>    {
</span><span>119</span>         <span>return</span><span> [];
</span><span>120</span> <span>    }
</span><span>121</span> 
<span>122</span>     <span>/*</span><span>*
</span><span>123</span> <span>     * Runs an action within this controller with the specified action ID and parameters.
</span><span>124</span> <span>     * 控制器中运行指定的操作标识和参数。
</span><span>125</span> <span>     * If the action ID is empty, the method will use [[defaultAction]].
</span><span>126</span> <span>     * 如果没有定义ID,会调用默认操作
</span><span>127</span> <span>     * @param string $id the ID of the action to be executed. 要执行的动作标识。
</span><span>128</span> <span>     * @param array $params the parameters (name-value pairs) to be passed to the action.
</span><span>129</span> <span>     * 传递给操作的参数。
</span><span>130</span> <span>     * @return mixed the result of the action.  操作结果
</span><span>131</span> <span>     * @throws InvalidRouteException if the requested action ID cannot be resolved into an action successfully.
</span><span>132</span> <span>     * @see createAction()
</span><span>133</span>      <span>*/</span>
<span>134</span>     <span>public</span> function runAction($id, $<span>params</span> =<span> [])
</span><span>135</span> <span>    {
</span><span>136</span>         $action = $<span>this</span>->createAction($id);<span>//</span><span>创建操作</span>
<span>137</span>         <span>if</span> ($action === <span>null</span>) {<span>//</span><span>创建失败,抛出异常</span>
<span>138</span>             <span>throw</span> <span>new</span> InvalidRouteException(<span>'</span><span>Unable to resolve the request: </span><span>'</span> . $<span>this</span>->getUniqueId() . <span>'</span><span>/</span><span>'</span><span> . $id);
</span><span>139</span> <span>        }
</span><span>140</span> 
<span>141</span>         Yii::trace(<span>"</span><span>Route to run: </span><span>"</span> . $action-><span>getUniqueId(), __METHOD__);
</span><span>142</span> 
<span>143</span>         <span>if</span> (Yii::$app->requestedAction === <span>null</span><span>) {
</span><span>144</span>             <span>//</span><span> 记录当前的操作为requestedAction</span>
<span>145</span>             Yii::$app->requestedAction =<span> $action;
</span><span>146</span> <span>        }
</span><span>147</span> 
<span>148</span>         $oldAction = $<span>this</span>->action;<span>//</span><span>将操作中的信息保存</span>
<span>149</span>         $<span>this</span>->action = $action;<span>//</span><span>写入属性
</span><span>150</span>         <span>//</span><span>保存当前控制器的所有父模块</span>
<span>151</span>         $modules =<span> [];
</span><span>152</span>         $runAction = <span>true</span><span>;
</span><span>153</span> 
<span>154</span>         <span>//</span><span> call beforeAction on modules 从外到里一层层执行module的beforeAction</span>
<span>155</span>         <span>foreach</span> ($<span>this</span>->getModules() <span>as</span><span> $module) {
</span><span>156</span>             <span>if</span> ($module-><span>beforeAction($action)) {
</span><span>157</span>                  <span>//</span><span> 将执行成功的module放入到$modules中,顺序会颠倒</span>
<span>158</span> <span>                array_unshift($modules, $module);
</span><span>159</span>             } <span>else</span><span> {
</span><span>160</span>                  <span>//</span><span> 执行失败,就标记一下</span>
<span>161</span>                 $runAction = <span>false</span><span>;
</span><span>162</span>                 <span>break</span><span>;
</span><span>163</span> <span>            }
</span><span>164</span> <span>        }
</span><span>165</span> 
<span>166</span>         $result = <span>null</span><span>;
</span><span>167</span> 
<span>168</span>         <span>if</span> ($runAction && $<span>this</span>-><span>beforeAction($action)) {
</span><span>169</span>             <span>//</span><span> run the action 执行成功就执行action</span>
<span>170</span>             $result = $action->runWithParams($<span>params</span><span>);
</span><span>171</span>             <span>//</span><span> 执行controller本身的afterAction</span>
<span>172</span>             $result = $<span>this</span>-><span>afterAction($action, $result);
</span><span>173</span> 
<span>174</span>             <span>//</span><span> call afterAction on modules 从里到外一层层执行所有</span>
<span>175</span>             <span>foreach</span> ($modules <span>as</span><span> $module) {
</span><span>176</span>                 <span>/*</span><span> @var $module Module </span><span>*/</span>
<span>177</span>                 $result = $module-><span>afterAction($action, $result);
</span><span>178</span> <span>            }
</span><span>179</span> <span>        }
</span><span>180</span> 
<span>181</span>         $<span>this</span>->action =<span> $oldAction;
</span><span>182</span> 
<span>183</span>         <span>return</span><span> $result;
</span><span>184</span>     }

yii2baseController.php

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1131347.htmlTechArticleyii2 source code study notes (11), yii2 source code study notes The Controller class is the base of all controllers Classes for calling models and layouts. 1 ? php 2 /* * 3 * @link http://www....
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'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.

PHP and Python: Code Examples and ComparisonPHP and Python: Code Examples and ComparisonApr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP in Action: Real-World Examples and ApplicationsPHP in Action: Real-World Examples and ApplicationsApr 14, 2025 am 12:19 AM

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.

PHP: Creating Interactive Web Content with EasePHP: Creating Interactive Web Content with EaseApr 14, 2025 am 12:15 AM

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python: Comparing Two Popular Programming LanguagesPHP and Python: Comparing Two Popular Programming LanguagesApr 14, 2025 am 12:13 AM

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.

The Enduring Relevance of PHP: Is It Still Alive?The Enduring Relevance of PHP: Is It Still Alive?Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

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尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

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

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.