search
HomeBackend DevelopmentPHP TutorialAnalysis of single entry application examples implemented by php_php skills

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.

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

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:

<&#63;php
define('APP', realpath('../libs/website'));
define('LANG', 'gb2312');
define('DEBUG', 1);
require('../libs/flea1/basic.php');
run();
&#63;>

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:

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

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.

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

PHP's Current Status: A Look at Web Development TrendsPHP's Current Status: A Look at Web Development TrendsApr 13, 2025 am 12:20 AM

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP vs. Other Languages: A ComparisonPHP vs. Other Languages: A ComparisonApr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and FunctionalityPHP vs. Python: Core Features and FunctionalityApr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP: A Key Language for Web DevelopmentPHP: A Key Language for Web DevelopmentApr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

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)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools