search
HomeBackend DevelopmentPHP Tutorialcakephp execution process code interpretation

Recently, I need to use the cakephp PHP framework for my work. Since I have used it less before, and I recently read some manuals, I feel that some things in cakephp are not very clear, so I decided to take a look at its source code. Here is what I saw Some notes during the process

I think if you are interested in viewing this document, it is best to open the corresponding PHP file and compare it, otherwise you may not know what I am talking about.

Start:

When we download and install by default from the Internet, there will be three directories: app, cake, vendors, as well as .htaccess, and index.php files.

According to the manual instructions and experience, the cake directory is the core code of the framework and is also a directory that does not need to be touched during development. This will be helpful for us to upgrade the framework core in the future. If you need to write your own class during the development process, you can place the file in the vendors directory and call it using methods such as app::import. .htaccess and index.php will pass the default access request to the app/webroot/index.php file for execution (if the server does not support .htaccess, you need to modify the index.php file again). Finally, we can determine that app is our default Main battlefield! (Of course this can be changed, for example, if several applications share a core, I won’t go into details here)

When opening the app/webroot/index.php file, we will find that this file writes It is very simple. The first piece of code defines some basic path constants (such as app path, directory path, etc.), followed by a cake/bootstrap.php file, which is this file that loads all the necessary information and initialization of the framework. Work, let's see what it does. B 是 Below is part of the code in the bootstrap.php file. I appropriately add some comments

If (! Isset ($ BOOTSTRAP)) {

Require core_path. 'Cake'. Ds. 'Basics.php' ; //Defines the common function methods of the framework

                                                                           . 'Object.php'; // The parent class of all classes

Require Libs. 'Inflector.php'; // Naming category, handling single plural hump naming: For example
                                                                                               ,,,,                                      ,,,                  ,,,,            ,,,              require LIBS . '; //Load cache engine class

                                                       use using ‐ ‐ ‐ ‐ ‐‐‐‐‐‐‐‐'; ​          'Core', array('Dispatcher')); //Import path processing class, program entry path, etc.

At the end of the app/webroot/index.php file, the $Dispatcher->dispatch method will be called to execute the program
$Dispatcher = new Dispatcher(); //Initialize the path processing class
$Dispatcher->dispatch($url); //The framework starts to determine the URL execution program

Let's see how the framework loads Dispatcher and executes the program!

First we will find the dispatch method in line 106 of the cake/ dispatcher.php file. By default, the parameters we pass to dispatch will be empty. When the url parameter is empty, the framework will automatically call the getUrl method to get URL and other information

Code such as:

$url = $this->getUrl(); //Get the URL path
$this->params = array_merge($this->parseParams($url), $additionalParams); //Get the processed URL Arrays, including values ​​passed by $_POST and $_GET, as well as controllers and methods. The program processes URL parameters through the parseParams method and calls the routes class method to obtain controller and action information, assemble it into a regular array, and pass it to $this- >params, it is worth noting that in the following code, $this->params will be assigned to $controller->params, which is why we can use $this->params in the controller. For example: $this->params['controller'] will get the controller name of the current request
Then the current action will be judged. For example, if there is an underscore (_) before the action name, it will be considered a protected method and will not be used. Access, etc.
Next, some parameters will be assigned to the current controller. The code is as follows
$controller->base = $this->base;
$controller->here = $this->here;
$controller ->webroot = $this->webroot;
$controller->plugin = $this->plugin;
$controller->params =& $this->params; //Pass all parameters to $controller->plugin, including controller and action names, form data, URL, etc.
$controller->action =& $this->params['action'];
$controller->passedArgs = array_merge($ this->params['pass'], $this->params['named']); //Assign all parameters passed by $_GET to $controller->passedArgs, including whether there are named parameters, such as /controller /action/a:1/b=2/3/4

(Note: When the controller executes the render method, it will automatically pass some variables to the view, which is what we call the template. For example, the controller will assign the value of the passedArgs variable. Give passedArgs in the view, so that we can directly call $this->passedArgs in the template)

It should be noted here that the framework will determine whether there are $_POST, $_GET and other values ​​​​in the current operation. For example, $_POST has a field name For the data field, the framework will execute $controller->data =& $this->params['data'];

The last modified method will call the current controller and pass the parameters for execution

The code is as follows: return $this- >_invoke($controller, $this->params); //Pass parameters to $controller through address reference, call $controller, and officially execute


Let’s take a look at the called _invoke

function _invoke(&$controller, $params)


function _invoke(&$controller, $params) {

$controller->constructClasses(); //Load controller necessary information and merge appController, etc. (including loading model, helper and Component), more information Please check the class method under controller.php

$controller->Component->initialize($controller); //Call component's initialize method before controller beforeFilter
$controller->beforeFilter();
$controller ->Component->startup($controller);

Here we can see that $controller->Component->initialize is executed before $controller->beforeFilter(), as shown in this manual I won’t say much more when it comes to mentioning it. What should be noted here is that the $controller->constructClasses method will merge the current user-defined controller class and some variables in AppController (app_controller.php), such as $users, helper and component, etc. , the more important thing here is that it will cycle through all the values ​​under the $users variable and load the corresponding model. If the $this->uses variable is false, no model will be initialized: Note that if you only want to define the controller and do not want to define the corresponding model file, this variable should be empty, or if you want to automatically load other models when the controller is called, you can assign the desired model name to $this->users=array(' modelname1', 'modelname2'), etc. Another situation is that when the user does not set the value of $users himself, the framework will automatically try to call the corresponding model based on the name (the model file is not necessary, but at this time in the database There must be a corresponding table, otherwise an error will be reported)


Other explanations should not be required

The following

$output = $controller->dispatchMethod($params['action'], $params['pass ']);
This method is to call the dispatchMethod method in the object class. In fact, the controller class executes the corresponding action method

The following is a small piece of code

if ($controller->autoRender) {
                                                                                                                                         output = $ output; When the time comes, the framework will call the render function to call the corresponding template to display and output the final HTML


The execution steps of the framework are basically over. Of course, there are still many things that have not been written in. Firstly, my writing skills are limited, and secondly, calling There are too many functions, so I won’t explain them one by one here.

This is just a simplified execution process, and does not involve model and other content. You can use it as a reference, because sometimes I feel uncomfortable reading the source code. It is easier to understand than reading the manual

The above is the content of cakephp execution process code interpretation. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


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 Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

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

Video Face Swap

Video Face Swap

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

Hot Article

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

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