PHP implementation of a single portal application case analysis _php skills

Source: Internet
Author: User
Tags diff http request switch case ruby on rails

This paper analyzes the PHP single entry application in detail. Share to everyone for your reference. Specifically as follows:

What is a single entry application?

Before we explain what a single entry application is, let's take a look at the traditional Web application.
news.php Display News list
news_edit.php Display News Edit page
Not only did the two pages achieve two functions, they also became the two portals of the application.

Then what is the entrance?

For example, everyone on the WC, are boys into a door, girls into a door. These two doors are the two entrances to the WC.

Oh, the above example should be very good understanding. The concept of a single entry is easy to understand if you change it a little.
Now we are in a public WC, whether men and women enter from the outermost entrance, after paying the money to enter two doors respectively. The outermost entrance is the single entrance to the WC.

So a single entry application is actually a file that handles all HTTP requests. For example, whether it's a news listing feature or a news editing feature, you can access index.php files from a browser. This index.php file is a single entry for this application.

index.php How do you know which feature users are using?

Very simply, we can follow a specific parameter when we visit the index.php. For example, Index.php?action=news is the display of news listings, and Index.php?action=news_edit is the news editor.

In index.php, 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 takes the action argument from the URL. If no action argument is provided, set a default ' index ' as an argument.
The second line of code is to invoke different code files based on the $action parameters to achieve a single entry corresponding to the effects of different functions.

is the portal file for a single entry application complex?

Some friends may think that the index.php of a single entry program can be as complex as noodles, but it is a misunderstanding.
For example, my current application portal file has only the following lines:

<?php
define (' APP ', Realpath. /libs/website '));
Define (' LANG ', ' gb2312 ');
Define (' DEBUG ', 1);
Require ('.. /libs/flea1/basic.php ');
Run ();
? >

Easy enough, huh?

Of course, writing a long list of switch case in index.php is definitely a poor way to implement it. But this is purely a design and implementation issue for the developer, not a single portal application design idea.

Add: This refers to switch case is not said to use the switch on behalf of "backward", "rustic" and so on. Just say in index.php this entry program to write a bunch of switch case is not conducive to program modification and maintenance, so it is a bad use.

Design idea of single entry application

When a Web server (Apache or IIS) receives an HTTP request, it resolves the request to 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 results to the browser. Now looking at the index.php file for a single entry application, you will find that index.php actually performed a second resolution based on the URL parameter.

The process of completing this parsing is generally called Dispatcher (I do not know the exact translation of Chinese), which presumably means forwarding different requests to different handlers for processing.

In a single portal application, index.php and the Web server form a Dispatcher that determines the requested handler based on the HTTP request and URL parameters.

Having learned the concept of Dispatcher, we can see that the two lines of code mentioned above are actually one of the simplest Dispatcher implementations:

<?php
$action = $_get[' action '] = = '? ' Index ': $_get[' action '];
Include (' files/'. $action. '. php ');
? >

Admittedly, for a secure, robust application, Dispatcher is certainly not as simple as it is. Before the actual code is invoked, a variety of judgments, security checks, and so on are added. For example, to determine whether the function specified by the URL can be accessed and the URL contains invalid parameters.

See here, friends will certainly say: A single entry program on such a dispatcher, and I directly made news.php, news_edit.php, such as a single document compared to what is the advantage ah?

Advantages of a single portal application

All HTTP requests for a single portal application are received and forwarded to the functional code via index.php, so we can do a lot of actual work in index.php.

Here, I'll just take a security check as an example to specify:

Because all HTTP requests are received by index.php, a centralized security check is possible. 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 to another file, just include in).
But I think everyone is lazy, perhaps memory is not good, it is inevitable to forget the time. So it's not easy to remember to add the necessary include in front of each file.

Similar to security checks. In the entrance, we can also do the necessary checks on URL parameters and post and special character filtering, logging, access statistics and so on all kinds of tasks can be centralized processing.

"Gee, do so many functions, not will make index.php complicated?" ”
"Not at all." Only need to write a variety of functions to a separate file, and then inside the index.php include in it! ”

As you can see, as these efforts are focused on the index.php to complete, we can reduce the difficulty of maintaining other functional code. For example, it is not pleasant to keep several of the headers in 10 files consistent with the same number of include.

Disadvantages of a single portal application

There are two sides to everything, and a single entry application is no exception. Because all HTTP requests are for index.php, the URL of the application does not look so good. Especially for the search engine is very unfriendly.

To solve this problem, we can use URL rewriting, pathinfo and so on. But I personally recommend that you do not use a single entry in the foreground page, but rather maintain multiple file portals. Or a mix of both. For example, the news list uses the individual news.php display, but the user registers, publishes the information and so on uses the single entrance. Because for the site owner, news list, news display page is the need for search engine attention to the high value of the target, and user registration page and other interactive functions are not included in the value.

A friend mentioned that a single entry application would have a long string of parameters, so let's analyze the following URL:
Index.php?url=news&news_id=123&page=2&sort=title
If you change the direct access to news.php, you simply omit the url=news parameter.

So it makes no sense to think that a single entry application URL is too complex.

How do I organize the functional code for a single entry application?

The biggest challenge for a single portal application is how to properly organize the processing code for each feature. But if you follow certain steps, you can easily solve the problem.

First of all, to make a reasonable decomposition of the functionality of the application. For example, the background news column may contain "Add News", "Edit News", "Delete News" and many other functions. In this case, we can combine this set of logically related functions into a functional module called the "News management" module.
By finishing the function of the application as described above, we will get multiple functional modules, each of which is composed of several functions. (In fact, even if it's not a single portal application, it's a necessary step to organize the functionality.) )

Once the functionality is sorted out, we need to determine how to store the code for each feature. Here I recommend two ways:

1, each function module a subdirectory, each file in the directory is a function of the implementation code.
The advantage of this approach is that each feature's code is isolated from each other, making it very convenient for many people to collaborate. The disadvantage is that it is less convenient to share code and data between each feature. For example, all the functions in the News management module need a "Take out the news column record" function, then adopt this multiple independent file organization way, "Take out the news column record" Can only write in another file, then by the need that function file include.

2. Each module is a file, each function in the module is written as a function or a class method.
The benefits are needless to say, making it easy to share code and data. The disadvantage is that if several people change at the same time, it is easy to conflict. However, conflict is easy to solve with version control software and diff diff consolidation Tools.

Well, our functional code is all determined by the way it is stored. So how do you call it?

index.php How do I invoke the functional code?

The first call is to design a rule, and then let index.php search and invoke the feature code based on this rule. For my own part, I always use $_get[' url ' to specify the function module to invoke, and $_get[' action ' to specify the specific functionality of the module. So my application uses the following URL address:
Index.php?url=news&action=edit

Think two parameters are too many? You can use a URL like index.php?func=news.edit. Just take the News.edit apart for news and edit.

"Hey, then I deliberately get a index.php?url=news&action=xxx, see your application can still run?" ”
Obviously, such a URL will only make index.php unable to find the required functional code, the final report error. But what is the essential difference between this and the newsxxx.php file you visit in the browser?

Instead, I can get index.php to display a nice error page when I can't find the functional code I need, and to provide a link back to the home page of the site.

In actual development, I tend to extract some basic services from the application to form an application framework. This framework typically includes a Dispatcher, basic database Access Service, template engine, common accessibility, and more. With a framework, I can make Dispatcher more flexible. For example, you can apply permission checks to some functional modules, while others do not.

Learn more about single entry applications

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

You can choose to implement a Dispatcher as well as the corresponding rules, or choose an existing application framework. But the better way is to try the existing framework first, and then try to implement a similar one yourself. This can be in the shortest possible time to get the most harvest.

The vast majority of PHP application frameworks are now single entry and use the MVC pattern (unfortunately, because MVC is too complex and not necessarily connected to a single portal application, I don't go into it.) 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 that this framework will be a very easy (if not easiest) framework.
All Chinese code annotations, simple structures, and streamlined code are the advantages of the fleaphp framework.

Cakephp
http://www.cakephp.org/
A Ruby on Rails PHP replica. has outstanding function, but obviously too complex, and lack of Chinese information is a big problem.

Symfony
http://www.symfony-project.com/
A very complex framework that integrates n many things. The video demo provided on the project site looks good.

Other
There are Mojavi, phing and many other PHP frameworks, if you are energetic, you can explore.

I hope this article will help you with your PHP program design.

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.