Designing PHP Project rationally with encapsulation class--on encapsulation of class in PHP project

Source: Internet
Author: User
Tags file system functions sql net variables string version zend
Packaging | design | Project coding is not a difficult task for qualified PHP programmers (perhaps just a matter of time), so the system analysis and design phase becomes particularly important. However, this article does not intend to discuss and demand analysis, access to business logic related topics, but to the system design aspects of the discussion.
Face problems
Coding is not difficult for qualified PHP programmers (perhaps just a matter of time), so the system analysis and design phase becomes particularly important. For a system analyst who acts as a PHP project, there are two challenges:

Limitations of the PHP language itself.
This is particularly noticeable in the object-oriented design of complex systems. The object-oriented nature of PHP, although improved in the existing version, is not robust enough to serve as an object-oriented design implementation language; Even if the vision is long, in the upcoming release of the Zend Engine 2.0 support of the new PHP, Object-oriented features will not be as popular as Java or C + + (see my other article on the Developerworks China Web site for this content). But if you adopt a completely process-oriented approach to Web pages, you can imagine that the design of the entire system is complex, and the resulting coding complexity and maintenance difficulties are more difficult to cope with.
A serious lack of available information.
This is a well-known phenomenon that the system design data for Web projects is insufficient, and in these limited data, the design information about PHP is very scarce. If the company or I do not have the relevant technology accumulation, system analysts can only find ways in the dark (worse two cases, one is to copy other projects such as Java or C + + design, the second is to think that the project simple and irresponsible hastily).

Recognizing the system facing
So, what is the best way to handle the analysis and design of PHP systems? The original idea should be to distinguish between the types of project commitment tasks:

Projects that involve a large number of customers themselves or the business logic of the customer's industry, including office systems, order systems, and other business systems.
Simple Web site projects, including projects that require high levels of traffic or require quick response, such as branded or active sites, and other sites.
Comprehensive website Project. Usually contains a number of relatively independent subsystems such as news subsystem, forum subsystem, product display subsystem and so on.

PHP is designed to address the urgent needs of the latter two projects, the language itself for these projects have been a good transformation. Many PHP developers have more or less experience with these projects, and most of the examples in related books revolve around this. Relative to the first system all the information is not much, the various publications on its content is rarely mentioned. So in this article, the first type of project is described in detail (about the MVC pattern and the class encapsulation), along with a reference to the second project (about hacking code) and the design method of the third project. Of course, not all of these items are categorized in the way described in this article, and the system analyst needs to weigh the various factors to choose.

Programme I: Involving a large number of business logic projects
How do I detach the user interface and background operations? How do you avoid confusing business logic with general process control? As a rigorous commercial project, many similar issues need to be considered. Implementing the design of the Model-view-controller (MVC) pattern is a great way to implement this type of project that is played by PHP.

Theoretical description
Here I don't want to explain the MVC pattern itself--simply literally and in application, by dividing the design of the system into model/logic, view views/interfaces, controller control/flow three logical parts to achieve good project results, In order to facilitate the work of the various parts of the developers and reduce future maintenance costs. (If you are familiar with JSP development Model 2 mode, you can find that it is also a good embodiment of the MVC pattern.) As far as realistic project development is concerned, the major problems that exist include the staggered and conflicting work of web designers and developers, and the fact that business logic embedded pages are not reusable and difficult to maintain, and so on. The introduction of MVC pattern can be a clear direction for the overall design of the system, which is also a good guide for the development team's division of labor.

Since the overall structure of the system is logically divided into three parts according to the MVC pattern, there are also developers in the team for each part.

Developer role related system logic responsibilities
Web designer view View/interface design for all user interface page templates.
Control process Developer Controller control/process to write all PHP pages in the system process.
Business logic Developer model/Logic development system design of each class (in which the method).

As can be seen from the above table, the traditional web design and program development of the Personnel Division is broken and replaced by the system logic of the responsibilities. For web designers, responsibility has not changed, precisely because such a division avoids the previous dispute with the program designer, they complete only the page template, so just focus on the Pure Web page code (mainly HTML, perhaps other client code such as WML) without having to be server-side ? ... ? > Interference. The program designers are divided into two parts: it is easy to grasp the business logic developers, their task is based on the system analyst given the module (exactly the class method) to complete, in their hands PHP is more like a general programming language (such as Java) and the web has nothing to do with , it is difficult to accept the control process developers, their task is to implement system design when the system process, according to the input of the client to invoke the business logic (the corresponding class method) and the output of the updated interface (to design the page template to deal with), In their hands PHP can give full play to the advantages of the Web programming language.

Code Organization-related Topics
This concept is somewhat abstract and is difficult to accept without a demonstration of an instance. Before giving an example, let me introduce my recommended code structure for this type of project:

Level two directory level three directory notes
/project_name Project source code root directory
/templates page Template Catalog (View)
Page templates under/admin/admin Management Console Directory
/include Business Logic Catalog (Model)
/temp Temporary Code directory (optional) for developers to test some test code
/images Picture Catalogue, page template adoption
/CSS style list, page template with
/scripts Client code directory, page template with
/admin Admin Console directory (optional), including all admin functional code
/other_dir corresponds to the/other_dir under the source code root, including the functional code that manages the class
/other_dir other directories related to the function, such as user-related/member directories or/PRODUCT directories related to products, etc.
/ Global configuration variables, defining global variables in the system
/ Security Policy control (optional)
/error.php Error Control return page (optional), or use static pages such as/error.html or other page names

Did you get a bit of a memory of using Java for Web development after reading it? For example, the classes directory and Lib directory in the Web-inf directory and Web.xml are all development rules--although PHP-enabled Web servers cannot automatically load files in these directories as the Java application Server does, the provision of an appropriate code organization pattern is very beneficial to the development of convenience and subsequent dimension To protect. (I started thinking about the code structure of the PHP project that was inspired by Tomcat's development manual.) )

Example of a user login
Based on the above code directory, the implementation of the MVC pattern described above can be explained more simply. Take the most common user logon feature, and imagine that there is a/member directory in the/project_name directory that contains everything about the user, It contains the login.php page that accepts the user's name and password used by the user to log on, and the index.php page is the user's homepage after the login is completed, and the error.php in the/project_name directory is the error display page after the logon failure.

Users through the other parts of the system to enter the user's home page, that is,/member/index.php page, this page to determine the user situation: the user has been logged in directly to the content of this page (can be used to check the session and other methods); The user who is not logged in requires login (redirect to/member/ login.php); An unknown error (redirect to/error.php) has occurred. At the same time take the corresponding reaction.
If the user is booted to the login page that is the/member/login.php page, the page accepts the user's login information (user name and password) and determines whether to log on correctly: The correct login is redirected again to the user's home page/member/index.php, and the login error is redirected to/ error.php.
If the user is booted to the Error Display page/error.php page (whichever page comes from), an error message will be displayed.

The flowchart shows the following:

Based on the above text descriptions and illustrations, combined with the implementation of the MVC pattern, you can easily write down the frame code of these several pages:

First look at the simple page/error.php:

And then the/member/login.php:

The last is/member/index.php:

(Note: The above code is only a fragment, and does not consider the project global, only play a role in demonstration)

About Controller
First of all, it is clear that the above three page code is the previous controller control/process code. Obviously, they do not contain a specific operation, there is no line of web code, there is only the same process control code with the previous flowchart (look, the common feature of these pages is filled with the Reference page template and output, get the object and execute a method or redirect).

Then select one of the pages/member/login.php the detailed explanation. The entire page is divided into two parts by deciding whether to submit the form: Displays the login form for the user to fill out and process the login information. As the former directly refers to a Web page template directory under the/templates of the page should be member_login.dwt and output after parsing, as the latter first get a member object (the object for Business logic directory/ Include in the, and then get the results of the login decision to redirect. In the code for this control page, MEMBER_LOGIN.DWT appears as a view/interface, and class member appears as model/logic, and the page code itself controller control/flow. Here is the/member/login.php frame code that adds the logo:

(About template classes and applications in the MVC pattern, you can refer to another article in this site, "Select the appropriate template in PHP")

About model
Now that we've talked about model, here's another important topic: the application of Class encapsulation in PHP projects.

Note the use of the word "class encapsulation"-which is fundamentally different from the "object-oriented" approach or any other method of "Object Design". "Class Encapsulation" simply describes how business logic is encapsulated into different classes by using a class approach, thus the "class" here does not adopt the "class" of object-oriented design--precisely, the "class" here is actually the result of merging a series of related functional modules.

Why not use the object-oriented approach and use this seemingly nondescript way to design the system? is PHP not an object-oriented feature? Yes, PHP has this feature, but very incomplete (you can refer to this site another article "from the Zend Engine 2.0 Design Blueprint (draft) to see the Future of PHP"). For example, PHP does not have the concept of interface and implementation methods, but also there is no multiple inheritance, method overload, such as typical object-oriented features. If you have to adopt object-oriented design methods, perhaps in the outline design phase can be very easy, but the detailed design phase will be more depressed, and if you are lucky to adhere to the coding phase is simply miserable. On the other hand, if the concept of the class is not introduced into the system, but rather the function is used to implement the module function, then it can be imagined how many functions will be in a medium and large system with such "pure", and the trouble is obvious.

or back to the PHP language itself. Although PHP does not provide real object-oriented support, it provides a definition of the class and its properties and methods. So it is natural to think of the use of class methods to encapsulate the relevant function modules, not only can learn from some of the advantages of object design, but also to avoid the full use of some of the shortcomings of the function module.

(Some systems that use functional modules will use the same method: write related functions in the same file, so that you can introduce separate files when referencing them.) For example, Member.func.php This file contains all the user-related actions, you can require the file before you process the user login, and then call functions such as Member_login (). But this kind of way only solves the system many function's code organization question, does not solve the name conflict question. Here's what you'll see in the example below. )

For example, in the above user login instance, if the method of function module is adopted, the code may be like this:

The method of class encapsulation may be this:

You might think that the code doesn't make any difference (even it seems that the code for the function module is more concise because it doesn't need to be a new object), but the real difference is that it happens in the include file. The function module is used to organize the related functions in a file (some systems do not do this, then it will create an extremely confusing situation), The class encapsulation method is used to declare a class with the same file name in each file (for example, a class that declares a member in This is similar to the Java rules), and when used, you need to include it first (if you don't have a good organization with a function module, some people might be "Easy" to include all functions included in every page--php is not a Java-like compilation and execution, it will take a while to parse these functions. The key, however, is that a class-encapsulated approach can clearly indicate the location of the call-a method (login) of a Class (member): This is very successful from the point of view of avoiding name collisions, and for code checking and maintenance, the convenience level is self-evident. Imagine a page that needs to do several functions, and it needs to include several files: The method of using a function module cannot easily find the function itself in the function call (if the function name or include file name does not have uniform rules, then this job is very difficult), The method of class encapsulation can precisely locate the code of class methods according to the class name and class file name. (You may think such a small benefit is trivial, but there may not be any objections after a maintenance project.) )

The above is the use of class packaging methods, the decision to use this method to design the system is only the first step, complete the design of the whole system there are many lessons to learn from.

Part of the design can draw on the object-oriented approach. Although there is no definition of interfaces and abstract classes in PHP, the inheritance mechanism is very incomplete, but at least it has the basic class definition and simple inheritance relationship. Obvious relationships such as "company-employee", "seller-buyer" can easily be defined in the system through class and class relationships. Since PHP can do this, define it according to the actual logical relationship.
Another situation that often occurs in the system is the relationship between the individual and the list-which may be difficult to understand, and imagine a relationship between a list of posts in a BBS system and each post. According to design experience, such relationships exist in a large number of PHP or other web systems. For this kind of relationship, I personally suggest that you can use the following item and Item_list class encapsulation method:
Item class definition: code
Item_list class definition: code
Because PHP has no syntax access restrictions (both public) on the class's member variables and methods, there is some confusion about object usage. Based on this, it is recommended that the code specification for the development team be defined to control this at the level of code application:
First, you can explain its properties by commenting on the member variables and methods, so that other developers who use the object can see if their usage violates the prescribed access restrictions. (If you use automated document generation tools such as Phpdoc, developers can even use it correctly by browsing the class documents without flipping through the class source.) )
Second, for the consideration of member variable access restrictions, you can declare some of the main variables that are frequently needed to be accessed or changed (in the comments) as public. This can save you the code for a lot of get () and set () methods-although this is considered very ugly in other object-oriented languages, remember that PHP is not Java and should be used boldly if it is reasonable.
You may have noticed the weight of the annotations from the example code above--although everyone understands the importance of annotations, it is still necessary to raise them. In this example, the Javadoc style is used, and the existing tools make it easy to generate documents directly (you and your development team can also define their own appropriate annotation styles and document generation tools). For a system analyst, the part of the code that you deliver to your development partner at the end of the design phase is likely to be the skeleton code for most of these annotations; the tools you communicate with are the most familiar codes and annotations of these programmers, in addition to the endless charts.

The design of the class in the PHP system, although not as much as building an object-oriented system requires a variety of reasonable patterns to intervene (and there is no such "cost" for it), but still need to ponder. Logical rationality and operational feasibility are the standards of inspection.

(When it comes to class design, you also think about the IDE that is suitable for PHP development.) As far as I know more professional some have Zend produced Zend IDE, there are also as JBuilder open tools appear with the help of the JBuilder PHP development tools, but the most commonly used is phped or ultraedit and other editors. If the existing editor can be very smart to support the PHP class design and code implementation is ideal. )

About view
Finally, the view aspect, although this part of the content and the Web designer contact more closely, but the PHP project (and other Web projects) system analyst must also pay attention to this topic. It can be seen that the application of the MVC pattern makes the results of Web developers and program designers not interact with each other as before, and naturally improves their work efficiency (the relationship may be more harmonious than before). But for system analysts, separating the user interface into individual Web templates requires a lot of analysis.

The first is to determine the process of the entire system, which should be done in the early stages of system design. For the View View/interface and controller control/flow, all required pages are generated around this process. But usually what you can see on the flowchart is that the relevant parameters are passed between the pages, but you don't know what the individual pages are showing--that's what the next step is to analyze the user interface.

In the analysis of the user interface, the first step can determine the core of each page, for the completion of the process essential user interface elements (Form and form fields, links, etc.), the second step is to determine the page needs to appear navigation content, and finally need to be based on process review. Or, for example, the user logged in above. For/member/ login.php This key page, the first step is to make sure that a form should be displayed before the user submits, that the form contains two text boxes for the user to enter the user name and password, and that after submission, the user interface is not required on this page and is replaced by the use of controller control/ The logical layer of the process is redirected. The second step is to develop the navigation links that you need to provide in this page (exactly when you are displaying the login form). Here you can add a link to the home page of the system or to the starting point of other unregistered user pages (for users to temporarily decide to cancel the login) and a link to log off existing users (for logged-in users). After the review, you may find that this design does not seem to take into account the better difference before the login is an administrator or a normal user login, then you can add a hidden field in the form to indicate whether the user who chooses to log on is ready to log on as an administrator or as a normal user.

Determining the elements of the user interface does not mean that the results can be delivered to the web designer, and that the most critical step is not implemented-the variable names needed to make the template for each page that the analysis finishes. For the above user login instance, if the system has the ability to identify the user who has logged in (based on the relevant cookie values set at the client's previous visit) and displays the user name in the user Name column of the login form, the Member_ The LOGIN.DWT design indicates that the form field will be assigned a template variable (for example, {USERNAME}). This step is completed and can be delivered to the Web designer for production.

It should be noted that some of the system designs that are likely to be part of the coding phase need to be modified, which may include modifications to the page templates that need to be carefully addressed.

Supplemental instructions for the Code organization
A few more documents and directories are not mentioned above: you are familiar with phpMyAdmin or other projects, you should be very aware of the role of this file: Define global variables within the scope of this project (include in each page). I personally think this is a very good design, so it is also advocated in the project application. In addition, to ensure conflict with other variables in the project, it is recommended that you define a multiple array in the file, and that all global variables appear with one of the values of the array. This makes it easier for other developers on the team to avoid the use of a variable name instead of avoiding the name of the variable that appears in all Another benefit of using this file is that the key variables, such as those related to the server environment, are centrally defined to facilitate the installation and porting of the entire project. file, as its name suggests, controls and enforces security policies for the entire system. With regard to security issues, you can think of two control scenarios: Control the page at the top of each control flow page and take control of the entire control file and be added to each control Flow page. I personally advocate the latter approach, and the reason is simple: simple and easy to maintain. Although the individual definition of each page may lose a little bit of efficiency (some pages that do not require security control need to include the file and be discriminated against), but gain the overall control of system security and the convenience of code maintenance (loss of a if...else ...). The judgment in exchange for such a result is still very worthwhile.
/temp-It is clear that the directory is a temporary file, and this directory does not actually appear in the official release of the project version. You can create a file in this directory if you are not very clear about the use of some functions during development, or if you experiment with code that has no relevant experience, because the directory is in the project code, it is very convenient to get the context of the project running, greatly reducing the cost of the test code.
/admin--Usually the admin content of the system should be placed in a separate directory, I personally prefer the abbreviated word (of course, there are some cases system analyst think should not set an easy to guess management directory name to increase the protection of the system security).
/css and/scripts-are all file repositories related to Web design, view views/interfaces, style sheets and client script respectively. The benefits of doing so are mentioned in any book that tells about Web site planning.

Scenario Two: Simple Web site projects
System performance is the primary goal of this type of project, while the maintenance and expansion of systems can hardly be considered at the same time. (Perhaps this sounds a bit absolute, but according to customer needs and the nature of the project to judge, to the maximum possible minimum time to meet customer demand and make the system efficient operation is the best test of project success.) So maybe this kind of project is a haven for PHP hackers (who used to be an overly demanding PHP user). Because of the specificity of such projects, the scope of this discussion is not limited to the system design but to the process of building the project team until the project is delivered.

The first thing to focus on is the person who participates in the project (although this may be the responsibility of the project manager, the system analyst who is most familiar with the characteristics of the PHP project should be involved). On the PHP developer side, at a minimum, you should choose developers familiar with PHP's various functions (such projects are not suitable as a real-world project to train participating developers), and it is even more desirable to have people who can understand PHP at the source level (although it is usually not possible for a typical PHP development company). For web designers, it's best to choose some of the people who have a bit of access to the client (such as JavaScript) and the server-side (preferably PHP) script, because one of the big features of such a project is that a single page has a large amount of code and a page code (usually HTML), Client script (such as JavaScript) and server-side scripts (such as PHP), the goal of adding a web designer that understands a variety of scripting languages is not to increase the team's PHP development power, but to avoid affecting the work of the program designer while modifying the Web page.

The second is the process-oriented, accurate page-oriented system design. Relative to the first type of project, the customer needs in this type of project performance is very clear, and the general long-term web development companies for such web site projects should also have a certain design experience accumulation. The design requires a process around the entire system, including the input parameters and output of each page (including functional links in addition to the navigation links appearing in the Web page) to fully meet the customer's needs; Another key is to determine system security policies, in which the user-level determination and access to the page are the primary priority. and gives the way to implement it. It should be noted, however, that it is not uncommon for such projects to return to the design phase from the coding phase, and that changes to local design (such as page incoming parameters or output links) should be controlled in a timely manner.

Finally, it is optimized for code and database. The hacker attitudes of developers need to be appropriately encouraged in such projects. The recommended approach is for the system analyst to give the pseudocode (frame code) for each page, while the local implementation is carried out by individual program developers and web designers.

For PHP code, you can usually consider the following:

The choice of algorithm and the way of function realization: module level optimization, can be discussed and solved by several developers;
The use of functions: code-level optimization requires developers to have a clear understanding of various functions, at least to develop a lot of reference function manual habits;
Database query and change is the use of SQL statements: If the company has the relevant database system managers, can be consulted on a number of optimization issues their suggestions;
Other issues to avoid: such as copying code, and other bad code.

In my experience, the hacker code that is usually written in this type of project is as follows:

Use of circular statements, especially when searching: notice the difference between while and for (presumably everyone has done this in college class), which is also a good programming habit;
SQL statement Optimization: The first is to try to avoid redundant database interaction, which is very important to improve efficiency, and secondly, do not be afraid of a few lines of statements rather than the use of so-called simple statements; Again, seriously consider the field returned by the query statement, reduce unnecessary data.
The acquisition of form submission values, such as check boxes and text fields. Sophisticated form domain name design can reduce the amount of code, while processing the submission value also need to pay attention to the way to deal with.

Hacker code should be encouraged in such projects, but it is best to attach as much detail as possible to each piece of code.

Because of the particularity of this kind of project, the key to complete the project is not only the system design stage, so it gives a simple description of the process of project start, system design, coding and testing and delivery.

Select the right person to form the project team and consider joining the sales and customer representatives.
A system analyst can simply summarize each page required by the system and describe its function by combining the customer's needs and previous project experiences, and determine the initial security strategy. This step allows you to join the sales staff and customer representatives. (At this point, the Web Designer is preparing a series of Web site image pages for customers.) )
The detailed design needs to determine the location and name for each page, and it is more critical to determine the input parameters and output as well as the exact access of users at different levels to the Web page. Database design at the same time. At a minimum, the process should provide a system flowchart (including access rights identification) and database design data.
Web designers and program developers get the relevant information to work on their own. For the former, each page is designed according to the customer's approved image, and for the latter, the "exciting" (because the code that requires an efficient profile, the hacker code) is coded. The difficulties encountered during this phase of the work need to be fed back to the system analyst and may return to the 3rd or 2nd steps above for design modification.
Program writing and web design after the end of the need for a period of integration, but also the program developers of the code to test themselves stage. At this stage, the code (including Web page code and program code) and database optimization work can be done. A complete system should be available at the end of this phase.
The real test phase is usually quite hasty, and the technology and experience of the company should also accumulate (if there are conditions to use some software tools for stability and compression testing). Finally, provide a web-accessible address for the customer to test. This phase is completed to provide a formal delivery system to the customer.

Programme III: Comprehensive Web site projects
There are already some large Web sites using PHP as the primary development language. For this type of project, simply from the PHP technology is worth proposing the topic is not much, in short or according to the site of the actual application of various parts (access intensity, operating behavior, etc.) to choose the above proposed two project design methods or integrated use. In addition, based on my personal experience, the organization and coordination of the project team, as well as the maintenance work after the completion of the project, are more critical factors than the simple technology.

For such projects, it can be suggested that proper adoption of some open-source software would be good for fast and quality project completion. Some parts of the project can be directly introduced into the Open-source software project design or even code, but only if the system designers have a good understanding of these introduced projects, but also need to do a good job of these isolated open source projects and the entire project interface (such as security policy considerations and global variable references, etc.).

For example, the following features are required for a consolidated web site according to customer requirements:

a complex press release;
An online forum that requires few management functions;
Simple product display;
User management is required.

(Obviously this is the embryonic form of a corporate website.) )

Of these, 1, 2 are obviously able to borrow some mature open source software projects, and 3 due to customer demand simple self-development compared with cost. As a result, 4 items are the most important part of the entire system-you need to do the user management integration work with 1, 2 Open-source software projects (3 is easy to integrate because of the reasons for self-development). (Some companies with better technology have even a simple solution for the integrated part mentioned above, so the cost of completing a Web site project is minimal.) )

A few special function points
There are also functional points that are usually present in the project but must be handled properly:

1. Data list paging.
On this feature, there are many Chinese and English materials on the Internet. Specific technical and implementation details do not need to be said, here only need to point out is:

A. The proposed method of encapsulating a tool class or other reusable form-the benefits are self-evident, and no one wants the system to have a stack of almost identical code as long as there is a page in the data list.

B. If some of the more efficient projects, such as the "Simple Web project" type mentioned above, should be used directly with PHP's own operational functions for a particular database system and the result set interception techniques associated with that database system (SQL statements), such as ' LIMIT start in MySQL ' , offset '; Other items that require a system to be designed neatly and reasonably (for example, "Designing a large number of business logic projects" mentioned above), if a common database interface is used, and for compatibility with a variety of database systems, this interface can be used to filter the result set, The loss of efficiency in exchange for better maintainability and scalability of the system. In other words, it is necessary to consider the performance and expansion of the system in order to implement the data list paging with the specific database operation function or the third party common database interface.

2. Error control.
This point is also mentioned in the above. In addition to creating an error class that belongs to a tool class, it is a good idea to create a special error display page. The page can be either a static HTML page (to express some of the user's apologies and processing instructions after the error) or a dynamic PHP page (can contain specific error causes and locations and other more detailed information, provided that this information is allowed in the system security Policy). The task of the error class is to accept the errors thrown in the normal program, and then redirect the information together on the error display page with the necessary processing.

At the same time, the establishment of error page for the development phase also has some benefits, can make up for the existing PHP lack of similar try{...} catch{the shortcomings of the block, the error in debugging or output through the error class thrown and displayed.

3. Upload and download.
For PHP, the upload implementation does not require Third-party program support, as is the case with other popular web development languages, and the built-in mechanism can be handled very simply. But here are a few of the more complex upload functions to implement. Examine one of the following processes for processing additional files:

This feature allows users to attach additional files when composing new messages, and to delete or continue to add files that have been attached before they are submitted. This requirement is reflected in many office-related systems, and as an experienced system analyst, an implementation plan for this type of functionality should be developed at the system design stage. For example, in the diagram shown in the process, is actually through one or more forms of each other submitted to complete (the specific design no longer repeat, to provide relevant PHP file reference; Another intuitive example is most free mail system add-on features, if interested can be inspected).

As for downloading, placing files in the server Web accessible directory and providing visitors with the true file path is the simplest solution; However, some systems in the download of files based on some security policies need to authenticate the identity side can be downloaded, such a way will bring hidden dangers. The usual approach may be to place files in a server file system other than the Web accessible directory or to store them in a database system--all requiring a simple program to get the contents of the file and return it directly to the requesting user (which involves some HTTP output headers. Provide a PHP file instead of a specific description). In the system design for different needs can be used to the appropriate approach.

4. Maintenance of client session sessions
The existing version of PHP already has built-in support for session, which is usually used in projects, and some special needs projects, such as distribution systems, may use a more complex approach.

On the client side, it is common to set up cookies to identify specific customers, and another way to handle clients that do not support cookies is to add a string that is sufficient to mark a particular customer with a URL rewrite. In this regard, the use of PHP built-in session support is ideal, because it can automatically fallback the client: If the client supports cookies, then it is natural; if the cookie is not supported, URL overrides are used--nothing requires developer intervention. If you adopt other session processing method, or write yourself to adapt to the needs of the session library, you need to pay attention to how to deal with the problem of client storage data--cookie or URL rewrite or both.

On the server side, it is simple to focus on the data that is associated with each specific customer that is labeled as a string--a variety of ways that can be used, usually in the form of files and databases. In PHP's built-in session support, the default support is to create a file for each customer in the system's temporary directory or directory to store its data, and, of course, to modify the way the settings support the database or otherwise. If you write the session library, choose a suitable storage mode according to the needs of the system. It is worth noting that for distributed systems, how to share server-side session information needs great attention.

In addition, when setting session variables, PHP's built-in session library supports objects as variable values (virtually all variable values, whether general variables or arrays or objects, are stored after serialization), i.e., the following code is available:

This is useful for some of the commercial systems mentioned above: first, you can store a set of information as a session variable value on the user's object, rather than a fragmented number of session variables; second, if you have a function like a shopping cart, The Cart object can be put into session in a way that is very consistent with the design of the entire system (i.e., the design of the commercial system described above, and the emphasis class encapsulation).

5 ..... Other functional points related to a particular project ...
While it is good to anticipate and resolve these features at the system design stage, even a small number of undiscovered feature points are not scary to leave behind in the coding phase--often such omissions do not affect the architecture of the entire system, but need to return to the design phase to include the appropriate content and documentation. After all, for the relevant project experience is not very rich system analyst, it is not realistic to realize this kind of function point in the design stage.

about other
There have been a lot of arguments about PHP, but since Java's dominance of the web has become more and more popular, the debate has come to a dead end-it seems that everyone has reached a consensus on the--php of rigorous business systems. However, based on this to blindly deny the application of PHP in the commercial system is also not objective, after all, PHP also has a low-cost advantage (here the cost includes development costs, use costs and maintenance costs). In addition to describing some of the PHP system design methods, the purpose of this article is to attract some developers or enterprises to use PHP to build a suitable business system.

In addition, this article is only a few of my own experience, if you see here when you have some ideas, I would be happy to share with you-to promote the development of open source software such as PHP without commercial support, after all, is a very exciting thing. (In this respect, I even want to write documentation and demonstration projects on PHP development, just as Sun Microsystems Blueprint and Java Pet store--for EE). Unfortunately, it is time, Energy and the limitations of personal ability--maybe the Spring Festival holiday is a good time:


Articles and code mentioned in this article
Code: User Login instance (including control page index.php,login.php; page template member_index.dwt,member_login.dwt; logical class related attachments;
Code: Class Encapsulation Instance (Item class defines;item_list class definition related attachments;
Code: Upload Instance (Control page add.php,attach.php) related attachments;
Code: Download Instance (Control page download.php) related accessories;
Code: Two global file (, related attachments in the instance Code organization;
Article: About the future of PHP;
Article: Templates used in PHP.
Other references
PHP official website--
Includes software and documentation, and usage, etc. (the most recent trend in this article is the release of Php 4.1.0, in some ways, a significant improvement).
Zend Company, which provides business support for PHP--
Contains PHP-related tools and text materials (you can find some topics related to this article).
The famous Open source project website soureforge--
A gathering place for open source projects, and provides web-based conveniences (you can find thousands of PHP-authored projects).

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