This article analyzes the PHP single-entry application in more detail. Share it with everyone for your reference. The details are as follows:
What is a single entry application?
Before explaining what a single entry application is, let’s take a look at a traditional web application.
news.php displays news list
news_edit.php displays the news editing page
These two pages not only implement two functions respectively, but also become two entrances to the application.
Then what is the entrance?
For example, when everyone goes to WC, boys enter one door and girls enter another door. These two doors are the two entrances to the WC.
Haha, the above example should be easy to understand. Then if you change it a little bit, the concept of single entrance is easy to understand.
Now we are entering a public WC. Both men and women enter from the outer entrance. After paying the money, they enter the two doors respectively. That outermost entrance is the single entrance to this WC.
So a single entry point application actually means using one file to handle all HTTP requests. For example, whether it is the news list function or the news editing function, the index.php file is accessed from the browser. The index.php file is the single entry point to the application.
index.php How to know which function the user wants to use?
It’s very simple, we just need to follow a specific parameter when accessing index.php. For example, index.php?action=news displays the news list, and index.php?action=news_edit represents the news editor.
In index.php, this effect can be achieved with only two lines of code.
<?php $action = $_GET['action'] == '' ? 'index' : $_GET['action']; include('files/' . $action . '.php'); ?>
In the above code, the first line is to take the action parameter from the url. If no action parameter is provided, a default 'index' is set as parameter.
The second line of code is to call different code files based on the $action parameter, thereby achieving the effect of a single entry corresponding to different functions.
The entry file for a single entry application is complicated?
Some friends may think that the index.php of a single-entry program will be as complicated as noodles, but this is actually a misunderstanding.
For example, my current application entry file only has the following lines:
<?php define('APP', realpath('../libs/website')); define('LANG', 'gb2312'); define('DEBUG', 1); require('../libs/flea1/basic.php'); run(); ?>
Simple enough, right?
Of course, writing a long list of switch cases in index.php is definitely a poor implementation. But this is purely a problem of the developer's own design and implementation, not a problem of the design idea of a single-entry application.
Additional explanation: The mention of switch case here does not mean that using switch means "backward", "fashionable", etc. It just means that writing a bunch of switch cases in the entry program index.php is not conducive to program modification and maintenance, so it is a bad usage.
Design ideas for single entry applications
When the web server (apache or iis) receives an http request, it will parse the request and determine which file to access. For example, the parsing result of http://www.xxx.com/news.php requires the web server to parse the news.php file and return the result to the browser. Now looking at the index.php file of the single entry application, you will see that index.php is actually parsed a second time based on the url parameters.
The program that completes this parsing is generally called Dispatcher (I don’t know the exact Chinese translation), which roughly means forwarding different requests to different handlers for processing.
In a single-entry application, index.php and the web server together form a Dispatcher, which determines the request handler based on the http request and url parameters.
After understanding the concept of Dispatcher, we can find that the two lines of code mentioned above are actually the simplest Dispatcher implementation:
<?php $action = $_GET['action'] == '' ? 'index' : $_GET['action']; include('files/' . $action . '.php'); ?>
Admittedly, for a secure and robust application, Dispatcher is definitely not as simple as the above. Before calling the actual code, various judgments, security checks, etc. will be added. For example, determine whether the function specified by the url can be accessed and whether the url contains invalid parameters.
Seeing this, friends will definitely say: There are more single entry programs. Just such a dispatcher, what are the advantages compared to me directly creating individual files such as news.php, news_edit.php, etc.?
Advantages of Single Entry Application
All http requests for the single-entry application are received through index.php and forwarded to the function code, so we can complete a lot of actual work in index.php.
Here I will only take the security check as an example to explain in detail:
Since all http requests are received by index.php, centralized security checks can be performed. If it is not a single entry, then the developer must remember to add the security check code at the beginning of each file (of course, the security check code can be written in another file, just include it).
But I think everyone is lazy, and maybe their memory is not good, so it is inevitable that they will forget sometimes. Therefore, it is not easy to remember to add the necessary include in front of each file.
Similar to security check. In the portal, we can also perform necessary checks on URL parameters and posts, filter special characters, record logs, access statistics, and other tasks that can be processed centrally.
“Hey, with so many functions, wouldn’t it make index.php very complicated?”
"No. Just write various functions into separate files, and then include them in index.php!"
It can be seen that since these tasks are concentrated in index.php, it can reduce the difficulty of maintaining other functional codes. For example, it is not pleasant to keep the include headers consistent in 10 files.
Disadvantages of Single Entry Applications
Everything has two sides, and single entry applications are no exception. Since all the http requests are to index.php, the url of the application does not look that pretty. Especially not friendly to search engines.
To solve this problem, you can use url rewriting, PATHINFO, etc. But I personally recommend not using a single entry method on the front page, but maintaining multiple file entries. Or a mix of the two. For example, the news list is displayed using a separate news.php, while user registration, posting information, etc. use a single entrance. Because for website owners, news lists and news display pages are high-value targets that require the attention of search engines, while interactive functions such as user registration pages have no value at all.
A friend mentioned that a single-entry application will have a long list of parameters, so let’s analyze the following URL:
index.php?url=news&news_id=123&page=2&sort=title
If you instead access news.php directly, you just omit the url=news parameter.
So it makes no sense to think that a single entry application url is too complex.
How to organize the functional code of a single entry application?
The biggest challenge of a single-entry application comes from how to reasonably organize the processing code of each function. But as long as you follow certain steps, you can easily solve this problem.
First of all, make a reasonable decomposition of the application’s functions. For example, the news column in the background may include multiple functions such as "add news", "edit news", "delete news", etc. At this time, we can combine this set of logically related functions into a functional module, called the "news management" module.
After sorting out the application's functions according to the above method, we will get multiple functional modules, and each module is composed of multiple functions. (In fact, even if it is not a single-entry application, the organization of functions is a necessary step.)
After organizing the functions, we need to determine how to store the code for each function. Here I recommend two methods:
1. Each functional module has a subdirectory, and each file in the directory is the implementation code of a function.
The advantage of this method is that the code of each function is isolated from each other, which is very convenient for multiple people to collaborate. The disadvantage is that it is not so convenient to share code and data between each function. For example, all functions in the news management module require a function of "retrieving news column records". With this organization method of multiple independent files, "retrieving news column records" can only be written in another file, and then Include the files that require this function.
2. Each module has one file, and each function in the module is written as a function or a class method.
Needless to say, the benefits are very convenient for sharing code and data. The disadvantage is that if several people make changes at the same time, conflicts may easily occur. However, conflicts can be easily resolved with the help of version control software and difference comparison and merge tools.
Okay, our function codes have been stored in a certain way. So how to call it?
How to call function code in index.php?
The first thing to call is to design a rule, and then let index.php search and call the function code according to this rule. For myself, I always use $_GET['url'] to specify the function module to be called, and $_GET['action'] to specify the specific function of the module. So my application will use the following url address:
index.php?url=news&action=edit
Think two parameters are too many? Then you can use a url like index.php?func=news.edit. Just split news.edit into news and edit.
"Hey, then I deliberately created an index.php?url=news&action=xxx to see if your application can still run?"
Obviously, such a URL will only make index.php unable to find the required function code, and finally report an error. But what is the essential difference between this and when you access the non-existent file newsxxx.php in your browser?
Conversely, I could also have index.php display a nice error page when it finds that it cannot find the required function code, and provide a link back to the homepage of the website.
In actual development, I tend to extract some basic services from the application to form an application framework. This framework usually includes a Dispatcher, basic database access services, template engine, common auxiliary functions, etc. Since I have a framework, I can make the Dispatcher more flexible. For example, permission checks can be applied to some functional modules and not others.
Learn more about single entry applications
To understand something deeply, the best way is to try it yourself.
You can choose to implement a Dispatcher and corresponding rules yourself, or choose an existing application framework. But a better way is to try an existing framework first, and then try to implement a similar one yourself. This way you can get the most bang for your buck in the shortest time.
At present, most PHP application frameworks are single-entry and adopt the MVC pattern (unfortunately, because MVC is too complicated and has no necessary connection with single-entry applications, I will not go into details. Interested friends can google the relevant information).
I personally recommend the following framework:
FleaPHP
http://www.fleaphp.org/
Well, I'm advertising. Because I made this framework. But I believe this framework will be a very easy to use (if not the easiest) framework.
Full Chinese code comments, simple structure, and streamlined code are the advantages of the FleaPHP framework.
CakePHP
http://www.cakephp.org/
A PHP knockoff for Ruby on Rails. It has excellent features, but is obviously too complex, and the lack of Chinese information is a big problem.
symfony
http://www.symfony-project.com/
A super complex framework that integrates n number of things. The video demonstration provided on the project website looks great.
Others
There are also many PHP frameworks such as Mojavi and Phing. If you are energetic, you can explore them.
I hope this article will be helpful to everyone’s PHP programming design.