Home Backend Development PHP Tutorial Source code analysis of YII (3)

Source code analysis of YII (3)

Aug 08, 2016 am 09:32 AM
gt index return this

I have already looked at the process of starting a Yii program and how to render a page. What we want to analyze today is how Yii handles user requests. That is the control and action part.

Let’s take helloworld as an example to demonstrate this process. We enter http://localhost/study/yii/demos/helloworld/index.php in the address bar, and the page displays hello world.

The previous analysis used the default value, but if the URL has parameters, how does Yii handle it? With this question in mind, let’s analyze it in detail.

There is this line of code in CWebApplication:

<span>$route</span>=<span>$this</span>->getUrlManager()->parseUrl(<span>$this</span>->getRequest());
Copy after login

This is the legendary route. Isn’t it a little bit chicken jelly? Let’s first take a look at how awesome getUrlManager is.

    <span>public</span> <span>function</span><span> getUrlManager()
    {
        </span><span>return</span> <span>$this</span>->getComponent('urlManager'<span>);
    }</span>
Copy after login

This requires finding a relationship again.

    <span>public</span> <span>function</span> getComponent(<span>$id</span>,<span>$createIfNull</span>=<span>true</span><span>)
    {
        </span><span>if</span>(<span>isset</span>(<span>$this</span>->_components[<span>$id</span><span>]))
            </span><span>return</span> <span>$this</span>->_components[<span>$id</span><span>];
        </span><span>elseif</span>(<span>isset</span>(<span>$this</span>->_componentConfig[<span>$id</span>]) && <span>$createIfNull</span><span>)
        {
            </span><span>$config</span>=<span>$this</span>->_componentConfig[<span>$id</span><span>];
            </span><span>if</span>(!<span>isset</span>(<span>$config</span>['enabled']) || <span>$config</span>['enabled'<span>])
            {
                Yii</span>::trace("Loading \"<span>$id</span>\" application component",'system.CModule'<span>);
                </span><span>unset</span>(<span>$config</span>['enabled'<span>]);
                </span><span>$component</span>=Yii::createComponent(<span>$config</span><span>);
                </span><span>$component</span>-><span>init();
                </span><span>return</span> <span>$this</span>->_components[<span>$id</span>]=<span>$component</span><span>;
            }
        }
    }</span>
Copy after login

Execute return $this->_components[$id]; The id is the urlManager passed in. In fact, you can’t see anything from here. Just find the urlManager class directly and look at parseUrl:

    <span>public</span> <span>function</span> parseUrl(<span>$request</span><span>)
    {
        </span><span>if</span>(<span>$this</span>->getUrlFormat()===self::<span>PATH_FORMAT)
        {
            </span><span>$rawPathInfo</span>=<span>$request</span>-><span>getPathInfo();
            </span><span>$pathInfo</span>=<span>$this</span>->removeUrlSuffix(<span>$rawPathInfo</span>,<span>$this</span>-><span>urlSuffix);
            </span><span>foreach</span>(<span>$this</span>->_rules <span>as</span> <span>$i</span>=><span>$rule</span><span>)
            {
                </span><span>if</span>(<span>is_array</span>(<span>$rule</span><span>))
                    </span><span>$this</span>->_rules[<span>$i</span>]=<span>$rule</span>=Yii::createComponent(<span>$rule</span><span>);
                </span><span>if</span>((<span>$r</span>=<span>$rule</span>->parseUrl(<span>$this</span>,<span>$request</span>,<span>$pathInfo</span>,<span>$rawPathInfo</span>))!==<span>false</span><span>)
                    </span><span>return</span> <span>isset</span>(<span>$_GET</span>[<span>$this</span>->routeVar]) ? <span>$_GET</span>[<span>$this</span>->routeVar] : <span>$r</span><span>;
            }
            </span><span>if</span>(<span>$this</span>-><span>useStrictParsing)
                </span><span>throw</span> <span>new</span> CHttpException(404,Yii::t('yii','Unable to resolve the request "{route}".',
                    <span>array</span>('{route}'=><span>$pathInfo</span><span>)));
            </span><span>else</span>
                <span>return</span> <span>$pathInfo</span><span>;
        }
        </span><span>elseif</span>(<span>isset</span>(<span>$_GET</span>[<span>$this</span>-><span>routeVar]))
            </span><span>return</span> <span>$_GET</span>[<span>$this</span>-><span>routeVar];
        </span><span>elseif</span>(<span>isset</span>(<span>$_POST</span>[<span>$this</span>-><span>routeVar]))
            </span><span>return</span> <span>$_POST</span>[<span>$this</span>-><span>routeVar];
        </span><span>else</span>
            <span>return</span> ''<span>;
    }</span>
Copy after login

Judging from the above code, if we don’t upload something to the url, we can just return ''. So the question arises, how to pass parameters?

isset($_GET[$this-><span>routeVar]) <br></span>
Copy after login
<span>public</span> <span>$routeVar</span>='r';
Copy after login

So we have a solution, let’s do some harm together. Add a parameter like helloworld/index.php?r=abc

Found an error. It means that the abc controller does not exist. In fact, it does not exist. It is just a little bad. As the saying goes, if a man is not bad, a woman will not love him.

Change to helloworld/index.php?r=site to display hello world. What the hell is this? The reason is very simple, because the site controller is defined.

<span>class</span> SiteController <span>extends</span><span> CController
{
    </span><span>/*</span><span>*
     * Index action is the default action in a controller.
     </span><span>*/</span>
    <span>public</span> <span>function</span><span> actionIndex()
    {
        </span><span>echo</span> 'Hello World'<span>;
    }</span><span>
}</span>
Copy after login

Okay, I have no objection to this, but what the hell is actionIndex? In Yii this is called an action. It captures the parameters behind the controller. If we enter ?r=site/index, it is index. The actions are separated by "/". In order to verify that I am not lying to girls, I control the site in the site Add an action to the device to show you:

<span>class</span> SiteController <span>extends</span><span> CController
{
    </span><span>/*</span><span>*
     * Index action is the default action in a controller.
     </span><span>*/</span>
    <span>public</span> <span>function</span><span> actionIndex()
    {
        </span><span>echo</span> 'Hello World'<span>;
    }

    </span><span>public</span> <span>function</span><span> actionView()
    {
        </span><span>echo</span> 'Hello View'<span>;
    }

}</span>
Copy after login

When accessing ?r=site/view, did you see the output 'Hello View'? It’s definitely true. Although I haven’t read many books, you can’t deceive me. There are pictures and the truth:

I don’t like using the name site at all, test is my favorite, so I built another test controller to try it out.

Those with sharp eyes must have seen how to write an action. What the hell is this? Only after I tried it did I realize that it is actually another way of expression.

I remember using it in the blog example to display the verification code:

    <span>/*</span><span>*
     * Declares class-based actions.
     </span><span>*/</span>
    <span>public</span> <span>function</span><span> actions()
    {
        </span><span>return</span> <span>array</span><span>(
            </span><span>//</span><span> captcha action renders the CAPTCHA image displayed on the contact page</span>
            'captcha'=><span>array</span><span>(
                </span>'class'=>'CCaptchaAction',
                'backColor'=>0xFFFFFF,<span>
            )</span>,
            <span>//</span><span> page action renders "static" pages stored under 'protected/views/site/pages'
            // They can be accessed via: index.php?r=site/page&view=FileName</span>
            'page'=><span>array</span><span>(
                </span>'class'=>'CViewAction',<span>
            )</span>,<span>
        );
    }</span>
Copy after login

I understand it as a collection of actions that centrally declare third-party businesses, because the actions in this controller are still straightforward in the form of action+ID.

What the hell? You said that I used index.php/site/captcha instead of index.php?r=site/captcha. This has to start with the configuration file.

        'urlManager'=><span>array</span><span>(
            </span>'urlFormat'=>'path',
            'rules'=><span>array</span><span>(
                </span>'post/<id:\d+>/<title:.*?>'=>'post/view',
                'posts/<tag:.*?>'=>'post/index',
                '<controller:\w+>/<action:\w+>'=>'<controller>/<action>',<span>
            )</span>,<span>
        )</span>,
Copy after login

urlFormat has two types: path and get. If it is not specified in main.php, then it is the get method, which is index.php?r=site/captcha. If specified, it will be something like index.php/site/captcha

It’s also easy to understand literally. path is in the format of a path, and get is in the form of ?.

There is a lot more to cover about the routing and controller parts, but that’s it for this section.

The above introduces the source code analysis of YII (3), including aspects of the content. I hope it will be helpful to friends who are interested in PHP tutorials.

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

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

What file is index.html? What file is index.html? Feb 19, 2024 pm 01:36 PM

index.html represents the home page file of the web page and is the default page of the website. When a user visits a website, the index.html page is usually loaded first. HTML (HypertextMarkupLanguage) is a markup language used to create web pages, and index.html is also an HTML file. It contains the structure and content of a web page, as well as tags and elements used for formatting and layout. Here is an example index.html code: &lt

What are the differences between Huawei GT3 Pro and GT4? What are the differences between Huawei GT3 Pro and GT4? Dec 29, 2023 pm 02:27 PM

Many users will choose the Huawei brand when choosing smart watches. Among them, Huawei GT3pro and GT4 are very popular choices. Many users are curious about the difference between Huawei GT3pro and GT4. Let’s introduce the two to you. . What are the differences between Huawei GT3pro and GT4? 1. Appearance GT4: 46mm and 41mm, the material is glass mirror + stainless steel body + high-resolution fiber back shell. GT3pro: 46.6mm and 42.9mm, the material is sapphire glass + titanium body/ceramic body + ceramic back shell 2. Healthy GT4: Using the latest Huawei Truseen5.5+ algorithm, the results will be more accurate. GT3pro: Added ECG electrocardiogram and blood vessel and safety

Detailed explanation of the usage of return in C language Detailed explanation of the usage of return in C language Oct 07, 2023 am 10:58 AM

The usage of return in C language is: 1. For functions whose return value type is void, you can use the return statement to end the execution of the function early; 2. For functions whose return value type is not void, the function of the return statement is to end the execution of the function. The result is returned to the caller; 3. End the execution of the function early. Inside the function, we can use the return statement to end the execution of the function early, even if the function does not return a value.

What is the execution order of return and finally statements in Java? What is the execution order of return and finally statements in Java? Apr 25, 2023 pm 07:55 PM

Source code: publicclassReturnFinallyDemo{publicstaticvoidmain(String[]args){System.out.println(case1());}publicstaticintcase1(){intx;try{x=1;returnx;}finally{x=3;}}}#Output The output of the above code can simply conclude: return is executed before finally. Let's take a look at what happens at the bytecode level. The following intercepts part of the bytecode of the case1 method, and compares the source code to annotate the meaning of each instruction in

Fix: Snipping tool not working in Windows 11 Fix: Snipping tool not working in Windows 11 Aug 24, 2023 am 09:48 AM

Why Snipping Tool Not Working on Windows 11 Understanding the root cause of the problem can help find the right solution. Here are the top reasons why the Snipping Tool might not be working properly: Focus Assistant is On: This prevents the Snipping Tool from opening. Corrupted application: If the snipping tool crashes on launch, it might be corrupted. Outdated graphics drivers: Incompatible drivers may interfere with the snipping tool. Interference from other applications: Other running applications may conflict with the Snipping Tool. Certificate has expired: An error during the upgrade process may cause this issu simple solution. These are suitable for most users and do not require any special technical knowledge. 1. Update Windows and Microsoft Store apps

How to Fix Can't Connect to App Store Error on iPhone How to Fix Can't Connect to App Store Error on iPhone Jul 29, 2023 am 08:22 AM

Part 1: Initial Troubleshooting Steps Checking Apple’s System Status: Before delving into complex solutions, let’s start with the basics. The problem may not lie with your device; Apple's servers may be down. Visit Apple's System Status page to see if the AppStore is working properly. If there's a problem, all you can do is wait for Apple to fix it. Check your internet connection: Make sure you have a stable internet connection as the "Unable to connect to AppStore" issue can sometimes be attributed to a poor connection. Try switching between Wi-Fi and mobile data or resetting network settings (General > Reset > Reset Network Settings > Settings). Update your iOS version:

php提交表单通过后,弹出的对话框怎样在当前页弹出,该如何解决 php提交表单通过后,弹出的对话框怎样在当前页弹出,该如何解决 Jun 13, 2016 am 10:23 AM

php提交表单通过后,弹出的对话框怎样在当前页弹出php提交表单通过后,弹出的对话框怎样在当前页弹出而不是在空白页弹出?想实现这样的效果:而不是空白页弹出:------解决方案--------------------如果你的验证用PHP在后端,那么就用Ajax;仅供参考:HTML code

How does Vue3 use setup syntax sugar to refuse to write return How does Vue3 use setup syntax sugar to refuse to write return May 12, 2023 pm 06:34 PM

Vue3.2 setup syntax sugar is a compile-time syntax sugar that uses the combined API in a single file component (SFC) to solve the cumbersome setup in Vue3.0. The declared variables, functions, and content introduced by import are exposed through return, so that they can be used in Vue3.0. Problems in use 1. There is no need to return declared variables, functions and content introduced by import during use. You can use syntactic sugar //import the content introduced import{getToday}from'./utils'//variable constmsg='Hello !'//function func

See all articles