SoFunction
Updated on 2025-03-09

Analysis of single entry application instances implemented by php

This article analyzes the PHP single entry application in more detail. Share it 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 traditional web applications.
Show news list
news_edit.php displays news editing page
These two pages not only implement two functions, but also become two portals for the application.

Then what is the entrance?

For example, when everyone goes to WC, boys enter one door and girls enter one door. These two doors are the two entrances to WC.

Haha, the above example should be easy to understand. Then, after a little change, the concept of a single entrance will be easy to understand.
Now we are entering a public WC. Both men and women enter from the outermost entrance and only enter two doors after paying the money. That outermost entrance is the single entrance to this WC.

So a single entry application is actually to use one file to process all HTTP requests. For example, whether it is the news list function or the news editor function, files are accessed from the browser. This file is the single entry to this application.

How do you know which function the user wants to use?

It's very simple, just keep up with a specific parameter when we access it. For example, ?action=news is to display a news list, and ?action=news_edit is the news editor.

And in it, this effect can be achieved with just 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, set a default 'index' as the parameter.
The second line of code is to call different code files according to the $action parameter, thereby achieving the effect of a single entry corresponding to different functions.

Is the entry files of a single entry application complicated?

Some friends may think that a single entry program will be as complicated as noodles, but it 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/');
run();
?>

Simple enough, right?

Of course, writing a long list of switch cases in it is definitely a clumsy way to implement it. But this is purely a problem with the developer's own design and implementation, not a problem with the design idea of ​​a single entry application.

Additional Note: The mention of switch case here does not mean that using switch means "backward", "rustic", etc. It just means that writing a bunch of switch cases in this entry program is not conducive to program modification and maintenance, so it is a bad use.

Design ideas for single entrance applications

When the web server (apache or iis) receives an http request, the request will be parsed to determine which file to access. For example, the parsing result of / is to require the web server to parse the file and return the result to the browser. Now look at the files of the single entry application and you will find that the second parsing was actually performed based on the url parameters.

The program that completes this analysis is generally called Dispatcher (I don’t know the accurate translation of Chinese), which roughly means forwarding different requests to different handlers for processing.

In a single entry application, together with the web server, a Dispatcher is formed, 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 implementation of Dispatcher:

<?php
$action = $_GET['action'] == '' ? 'index' : $_GET['action'];
include('files/' . $action . '.php');
?>

Admittedly, for a safe and robust application, Dispatcher is definitely not as simple as above. Before calling the actual code, various judgments, security checks, etc. will be added. For example, determine whether the function specified by url is accessible and that the url contains invalid parameters.

Seeing this, friends will definitely say: There are more single entry programs, just like this dispatcher. What are the benefits of making single files such as news_edit.php?

Advantages of a single entry application

All http requests for a single entry application are received and forwarded to the function code, so we can do a lot of practical work in it.

Here I will only use the safety check as an example to explain in detail:

Since all http requests are received by , centralized security checks can be performed. If it is not a single entry, then developers must remember to add security check code to the beginning of each file (of course, security check code can be written to another file, just include it).
But I think everyone is lazy, maybe they have a bad memory, so there is inevitably times when they forget it. Therefore, remember to include the necessary include in front of each file is not an easy task.

Similar to security checks. In the entrance, we can also perform necessary checks and special character filtering on the url parameters and post, logging, access statistics and other tasks that can be processed centrally.

"Hey, will you make it complicated by so many functions?"
"No. Just write various functions to a separate file and include it inside!"

It can be seen that since these tasks are concentrated to be completed, it can reduce the difficulty of maintaining other functional codes. For example, keeping the header include in 10 files consistent is not a pleasant thing.

Disadvantages of single entry applications

Everything has two sides, and a single entry application is no exception. Since all http requests are targeted, the application's url does not look that beautiful. Especially for search engines, it's not friendly.

To solve this problem, you can use url rewrite, PATHINFO, etc. But I personally recommend not using a single entry method on the front desk page, but keeping multiple file entry. Or use both. For example, news lists are displayed separately, while user registration, information publishing, etc. use a single entry. Because for website owners, news lists and news display pages are high-value targets that need search engines to pay attention to, while interactive functions such as user registration pages have no value inclusion.

Someone mentioned that a single entry application will have a long string of parameters, so let’s analyze the following url:
?url=news&news_id=123&page=2&sort=title
If you change to direct access, you will only save the parameter url=news.

So it doesn't make sense to think that a single-entertain entry application url is too complex.

How to organize the functional code of a single entry application?

The biggest challenge for 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, a reasonable decomposition of the functions of the application should be made. For example, the news column in the background may include multiple functions such as "Add News", "Edit News", and "Delete News". At this time, we can combine this set of logically associated functions into a functional module, called the "News Management" module.
After sorting out the functions of the application 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 sorting out the functions, we need to determine how to store the code for each function. Here I recommend two ways:

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 codes for each function are isolated from each other, which is very convenient for multiple people to collaborate. The disadvantage is that sharing code and data between each function is not that convenient. For example, all functions in the news management module require a function of "retrieve news column records". Then, using this method of organizing multiple independent files, "retrieve news column records" can only be written in another file, and then the file that requires the function is included.

2. Each module has a file, and each function in the module is written as a function or a class method.
Needless to say, it is very convenient to share code and data. The disadvantage is that if several people change at the same time, conflicts are prone to occur. However, with the help of version control software and the difference comparison merging tool, the conflict is still easy to resolve.

OK, our function codes have determined the storage method. So how to call it?

How to call function code?

The first thing to call is to design a rule, and then let the function code be searched and called 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 functionality of that module. So my application will use the following URL address:
?url=news&action=edit

Do you think there are too many two parameters? Then you can use urls like ?func=. Just break it into news and edit.

"Hehe, then I deliberately made one ?url=news&action=xxx to see if your application can still run?"
Obviously, such a url will only make it impossible to find the required function code and finally report an error. But what is the essential difference between this and your access to this non-existent file in your browser?

Instead, I can also let a nice error page be displayed when I find that the required feature code is not found and provide a connection 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 engines, commonly used auxiliary functions, etc. With a framework, I can make Dispatcher more flexible. For example, permission checks can be applied to some functional modules, while others do not.

Learn more about single portal applications

To deeply understand a thing, it is the best way to try it yourself.

You can choose to implement a Dispatcher yourself and various corresponding rules, or choose an existing application framework. But a better way is to try the existing framework first and then try to implement a similar one by yourself. This will get the most rewards in the shortest time.

Currently, most php application frameworks are single-entry and adopt the MVC mode (unfortunately, since MVC is too complex and has no necessary connection with a single-entry application, I won't google the relevant information. Interested friends can google it).

I personally recommend the following framework:

FleaPHP
/
Well, I'm advertising. Because I made this framework. But I believe this framework will be a very easy (if not the easiest) framework.
All Chinese code comments, simple structures, and streamlined code are all advantages of the FleaPHP framework.

CakePHP
/
A PHP copy of Ruby on Rails. It has excellent features, but is obviously too complicated, and the lack of Chinese materials is a big problem.

symfony
/
A super complex framework that integrates n many things. The video demonstrations provided on the project website look great.

other
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.