Analysis of a single entry application instance implemented by php

Source: Internet
Author: User
Tags switch case
This article mainly introduces the single-entry application implemented by php, and analyzes in detail the principles, functions, implementation principles and related skills of php to implement a single-entry application, it has some reference value. if you need it, you can refer to this article to analyze the single-entry php application in detail. Share it with you for your reference. The details are as follows:

What is a single portal application?

Before explaining what a single portal application is, let's take a look at traditional web applications.
News. php display news list
News_edit.php: Display the news editing page
These two pages not only implement two functions, but also become two portals for applications.

So what is the entrance?

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

The above example should be well understood. The concept of a single portal is easy to understand.
Now we are entering a public WC, regardless of whether men and women are entering from the outermost entrance. after paying the money, we will enter two separate doors. The outermost entrance is the single entrance of this WC.

Therefore, an application with a single portal actually uses a single file to process all HTTP requests. For example, whether the news list function or the news editing function, the index. php file is accessed from the browser. This index. php file is a single entry to this application.

How does index. php know which function is used by users?

It's easy. just keep up with a specific parameter when accessing index. php. For example, index. php? Action = news is to display the news list, and index. php? Action = news_edit is 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 retrieve the action parameter from the url. If the action parameter is not provided, a default 'index' is set as the parameter.
The second line of code is to call different code files according to the $ action parameter, so that a single entry can correspond to different functions.

Is the entry file of a single portal application complicated?

Some may think that the index. php of a single portal program is as complicated as a noodle, which is actually a misunderstanding.
For example, my current application portal file only contains the following lines:

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

Is it easy enough?

Of course, writing a long string of switch cases in index. php is definitely a poor implementation method. But this is purely a developer's own design and implementation, rather than a single portal application design.

Note: The switch case mentioned here does not mean that if a switch is used, it indicates "backward" and "rustic. Writing a bunch of switch cases in the index. php entry program is not conducive to program modification and maintenance, so it is a bad usage.

Design idea of a single portal application

When the web server (apache or iis) receives an http request, the request is parsed to determine which file to access. For example, the http://www.xxx.com/news.php resolution result is to require the web server to parse the news. php file and return the result to the browser. Now let's look at the index. php file of the single entry application, and we will find that index. php actually performs the second resolution based on the url parameter.

The program that completes this resolution is generally called Dispatcher (I do not know the exact translation of Chinese characters), which means forwarding different requests to different handlers for processing.

In a single entry application, index. php and the web server constitute a Dispatcher. the request processing program is determined based on the http request and url parameters.

After learning about the Dispatcher concept, 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');?>

Indeed, for a secure and robust application, Dispatcher is certainly not as simple as above. Before calling the actual code, various judgments and security checks will be added. For example, determine whether the function specified by the url can be accessed and whether the url contains invalid parameters.

When I see this, my friends will surely say: there is more than a single entry program, such as a dispatcher. What are the advantages of directly making a single file such as news. php and news_edit.php?

Advantages of a single portal application

All http requests of a single entry application are received and forwarded to the functional code through index. php. Therefore, we can complete a lot of practical work in index. php.

Here I will take the security check as an example to describe in detail:

Since all http requests are received by index. php, centralized security checks can be performed. If it is not a single entry, developers must remember to add the security check code at the beginning of each file (of course, the security check code can be written to another file, and only need to include it in ).
But I think everyone is a lazy person, and it may be hard to remember, and sometimes it is hard to forget. Therefore, it is not easy to add the necessary include before each file.

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

"Isn't index. php complicated to implement such a function ?"
"No. You only need to write various functions to a separate file and include them in index. php !"

As we can see, because these tasks are concentrated in index. php, we can reduce the difficulty of maintaining other functional code. For example, it is not pleasant to keep several include entries in the header in 10 files.

Disadvantages of a single portal application

Everything has two sides, and a single portal application is no exception. Because all http requests are for index. php, the url of the application does not look so beautiful. Especially unfriendly to search engines.

To solve this problem, you can use url rewriting, PATHINFO, and other methods. However, I personally recommend that you maintain multiple file portals instead of using a single portal on the front-end page. Or mix the two. For example, the news list is displayed in separate news. php, and the user registration and publishing information are displayed in a single portal. For website owners, News lists and news Display pages are high value targets that require search engines to focus on, while interactive functions such as user registration pages are not included in the value.

A friend mentioned that a single-entry application has a long string of parameters, so we can analyze the url below the comment:
Index. php? Url = news & news_id = 123 & page = 2 & sort = title
If you access news. php directly, the url = news parameter is saved.

Therefore, it is unreasonable to think that the url of an application with a single portal is too complex.

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

The biggest challenge for a single portal application is how to properly organize the processing code for each function. However, you can easily solve this problem by following certain steps.

First, make a reasonable decomposition of the functions of the application. For example, the background news section may contain "add news", "edit news", and "delete News. In this case, we can combine the logic-related functions of this group into a function module called the "news management" module.
After finishing 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, functional sorting is a required step, even if it is not a single portal application .)

After finishing the functions, we need to determine how to store the code of each function. Here I recommend two methods:

1. each function module has a sub-directory, and each file in the directory is a function implementation code.
The advantage of this method is that the code of each function is isolated from each other, so that it is easy for multiple people to collaborate. The disadvantage is that sharing code and data between each function is not that convenient. For example, all the functions in the news management module require the function of "retrieving news column records", so the organization of multiple independent files is adopted, "retrieve the news record" can only be written in another file, and then included in the file that requires this function.

2. Each module has a file, and each function in the module is written as a function or a class method.
It is easy to share code and data. The disadvantage is that, if a few people change at the same time, conflicts may occur. However, conflicts are easily solved by using version control software and comparison tools.

Okay, we have determined the storage method for all our functional code. So how to call it?

How does index. php call the function code?

First, you need to design a rule for calling, and then let index. php search for and call the function code according to the rule. For myself, I always use $ _ GET ['URL'] to specify the function module to be called, $ _ GET ['action'] specifies the specific functions of this module. Therefore, my application uses the following url:
Index. php? Url = news & action = edit

Think there are too many two parameters? So you can use index. php? Func = url like news. edit. You only need to split news. edit into news and edit.

"Hey, I mean to create an index. php? Url = news & action = xxx. can your application still run ?"
Obviously, such a url will only make index. php unable to find the required functional code, and finally report an error. But what is the essential difference between this and accessing the nonexistent file newsxxx. php in your browser?

On the contrary, I can make index. php display a beautiful error page when I find that I cannot find the required functional code, and provide a connection to return to the homepage of the website.

In actual development, I tend to extract some basic services from applications to form an application framework. This framework usually contains a Dispatcher, basic database access services, template engines, and common auxiliary functions. With a framework, I can make the Dispatcher more flexible. For example, you can check the application permissions of some functional modules, while others do not.

Learn more about single-entry applications

It is the best way to thoroughly understand a thing.

You can implement a Dispatcher and various rules on your own, or select an existing application framework. But the better way is to first try the existing framework, and then try to implement a similar one. In this way, you can get the most results in the shortest time.

At present, most php application frameworks use a single portal and adopt the MVC model (unfortunately, because MVC is too complex, and it is not necessarily related to a single portal application, so I won't go into details. If you are interested, you can google the relevant information ).

I personally recommend the following framework:

FleaPHP
Http://www.fleaphp.org/
Well, I am advertising. Because I did this framework. But I believe this framework will be very easy to use (even if not the easiest.
Full-Chinese code comments, simple structures, and simplified code are all advantages of the FleaPHP framework.

CakePHP
Http://www.cakephp.org/
A Ruby on Rails PHP counterfeit product. It has outstanding features, but it is obviously too complicated, and the lack of Chinese materials is a big problem.

Symfony
Http://www.symfony-project.com/
An ultra-complex framework that integrates n things. The video presentation provided on the project website looks good.

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 help you with php programming.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.