Use encapsulation classes to reasonably design PHP projects-about class encapsulation in PHP Projects

Source: Internet
Author: User
Tags php framework
Designing PHP projects with encapsulation classes: Class encapsulation in PHP Projects
 
Coding is not difficult for qualified PHP programmers (it may only take a long time). Therefore, this stage of system analysis and design is particularly important. However, this article is not intended to discuss the topics related to demand analysis and commercial logic, but to discuss the system design.

Difficulties
Coding is not difficult for qualified PHP programmers (it may only take a long time). Therefore, this stage of system analysis and design is particularly important. A system analyst for a PHP project faces two challenges:

  1. Restrictions on the PHP language itself.
    This is particularly significant in the object-oriented design of complex systems. Although PHP's object-oriented feature has been improved in the existing version, it is not sound enough to serve as the implementation language of object-oriented design, in the new PHP version supported by Zend engine 2.0 that will be released soon, object-oriented features will not be the same as the popular Java or C ++ (for more information, see another article I posted on the developerworks Chinese website ). However, if we adopt a completely process-oriented approach (specifically for Web pages), we can imagine that the design of the entire system will be very complicated, and the resulting complexity of coding and maintenance difficulties will be even more difficult to cope.
  2. Serious Lack of existing information.
    This is a well-known phenomenon, that is, insufficient system design materials for web projects. Among these limited materials, PHP design materials are scarce. If the company or myself do not have any technical accumulation, the system analyst can only find a way in the dark (two worse cases, one is to copy the design of other projects such as Java or C ++, the second is to think that the project is simple and irresponsible ).

Recognition System
In this case, how can we properly analyze and design the PHP system? The initial idea should clarify the types of tasks undertaken by the project:

  1. Projects that involve the business logic of a large number of customers themselves or their industries, including office systems, order systems, and other business systems.
  2. Simple website projects include projects that require high access traffic or fast response, such as brand websites or activity websites, and other websites.
  3. Comprehensive website project. It usually contains multiple relatively independent subsystems, such as the news subsystem, Forum subsystem, and product display subsystem.

The original intention of PHP is to solve the urgent needs of the latter two projects. The language itself has well transformed these projects. Many PHP developers have more or less experience in these projects, and most examples in related books are centered around this. Relatively speaking, there is not much information in the first system, and the content of various publications is rarely mentioned. Therefore, this article describes the first type of project in detail (about MVC mode and class encapsulation), and also mentions the second type of project (about Hacker code) and the third project design method. Of course, not classified projects can only be described in this document, and system analysts need to weigh various factors to choose from.

Solution 1: involving a large number of business logic Projects
How do I separate user interfaces from background operations? How can we avoid obfuscation of business logic in general process control? As a rigorous commercial project, many similar problems need to be considered. For such projects undertaken by PHP, implementing the Model-View-controller (MVC) pattern design is a very good method.

Theoretical description
Here I don't want to explain more about the MVC model itself-simply put, literally, by dividing the system design into three logical parts: model/logic, view/interface, and controller control/process, a good project effect is achieved, this facilitates the work of various developers and reduces maintenance costs in the future. (If you are familiar with the Model 2 mode developed by JSP, you can find that it is also a good embodiment of the MVC mode .) As far as practical project development is concerned, there are many major problems, including the staggered and conflicting work of web designers and program developers, and the unavailability and maintenance of business logic embedded pages. The introduction of the MVC model can provide a clear direction for the overall design of the system and provide good guidance for the division of labor among development teams.

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

Developer role Related system logic Responsibilities
Web designer View view/interface Design webpage templates for all user interfaces.
Control Process developers Controller Control/process Compile all PHP pages in the system flow.
Business Logic developers Model model/logic The classes (methods) specified in the development system design ).

From the above table, we can see that the division of labor of traditional web design and program development personnel is broken and replaced by the responsibilities defined according to the system logic. The roles and responsibilities of web designers have not changed. To be precise, this Division avoids previous disputes with program designers. All they do is webpage templates, therefore, you only need to focus on pure Web Page code (mainly HTML, and may have code from other clients such as WML) and do not need to be processed by the server. <? ... ?> Interference. Program designers are divided into two parts: business logic developers are easy to grasp, and their tasks are completed according to the modules (class methods) given by the system analyst, PHP in their hands is more like a general programming language (such as Java) and has nothing to do with the web; what is hard to accept at the moment is the control process developers, their task is to call the business logic (corresponding class methods) based on the client input while developing the system process during system design) and the output of the updated interface (processing the webpage template). in their hands, PHP can give full play to the advantages of WEB programming language.

Topics related to Code Organization
This concept is somewhat abstract, and it is difficult to accept demonstration without instances. Before giving an example, I would like to introduce the recommended code structure for such projects:

Level 1 directory Level 2 Directory Level 3 directory Remarks
/Project_name     Project source code root directory
  /Templates   Webpage template directory (view)
    /Admin Management Console Directory/Webpage Template under Admin
  /Include   Business Logic catalog (model)
  /Temp Temporary code directory (optional) for developers to test some test code
  /Images   Image directory, web template used
  /CSS   Style Sheet directory, webpage template used
  /Scripts Client code directory. The webpage template adopts
  /Admin   Management Console Directory (optional), including all functional codes for background management
    /Other_dir Corresponds to/other_dir under the source code root directory, including the functional code for managing this class
  /Other_dir   Other directories related to the corresponding functions, such as the/member directory related to the user or the/product directory related to the slave product.
  /Config. Inc. php   Global configuration variables: define global variables in the system
  /Security. Inc. php   Security Policy Control (optional)
  /Error. php   Error Control return page (Optional). You can also use static pages such as/error.html or other page names.

After reading this, have you aroused some memories of using Java for web development? For example, the WEB-INF directory classes directory and lib directory and web. XML is a rule in development-although the web server that supports PHP cannot automatically load files under these directories as the Java application server does, however, specifying an appropriate code organization mode is very helpful for the convenience of Development and subsequent maintenance. (I started to consider that the code structure of the PHP project was inspired by the Tomcat development manual .)

An example of User Logon
According to the above Code directory, the implementation of the MVC mode mentioned above can be explained in a simpler way. Take the most common user logon function as an example. Assume that the/member directory under the/project_name directory contains all functions related to users, including login. the PHP page accepts the user name and password used for user logon, index. the PHP page is the user homepage after logon, and the error in the/project_name directory. PHP is the error display page after logon failure.

  1. The user uses other system requests to access the user's homepage, namely/member/index. PHP page. At this time, the page determines the user's situation: logged-on users directly display the content of this page (you can check the session and other methods ); if you are not logged on, You need to log on (redirect to/member/login. PHP); an unknown error occurs (redirected to/error. PHP ). Respond accordingly.
  2. Assume that the user is directed to the logon page:/member/login. PHP page, which accepts the user's logon information (user name and password) and determines whether the logon is correct: the correct logon will be redirected to the user's homepage/member/index again. PHP; redirection to/error if a logon error occurs. PHP.
  3. If the user is redirected to the error display page/error. PHP page (no matter from which page is displayed), the error message is displayed.

The process diagram is as follows:

Based on the above text description and illustration, combined with the implementation of the MVC mode, you can easily write the Framework Code for these pages:

  1. First look at the simple page/error. php:
  2. Then/member/login. php:
  3. Finally,/member/index. php:
     

(Note: The above code is only a piece, and does not take into account the global project, it only serves as a demonstration)

About Controller
The above three page codes are the controller control/Process Codes mentioned above. Obviously, they do not include a specific operation or a line of Web code, and some are the process control code consistent with the previous flowchart (looking at it, the common feature of these pages is that they are full of referencing a webpage template, outputting, retrieving objects, and executing a method or redirection ).

Select one of the pages/member/login. php for detailed explanation. The entire page is divided into two parts by determining whether to submit the form: display the login form for users to fill in and process login information. The former directly references a member_login.dwt file in the webpage template directory/templates and outputs it after parsing; as the latter, first obtain a member object (this object is out of the member under the business logic directory/include. inc. PHP. In the code on this control page, member_login.dwt appears as the view/interface, and member as the model/logic, while the Page code itself controls the Controller/process. The following is the code of the/member/login. php framework with the label added:

(For template classes and applications in the MVC mode, refer to another article on this site, "select a suitable template in PHP".)

About Model
Now that we have talked about model, the following is another important topic: Application of classes encapsulated in PHP projects.

Note that the term "class encapsulation"-This is essentially different from the "Object-Oriented" or other "use Object Design" method. "Class encapsulation" only describes how to encapsulate business logic into different classes by class methods, therefore, the "class" here is not the "class" that emerged from the object-oriented design-to be accurate, the "class" here is actually the result of merging a series of related functional modules.

Why does it not directly adopt an object-oriented approach but such a seemingly nondescribable approach to design the system? Isn't PHP object-oriented? Yes, PHP has such features, but it is very incomplete (you can refer to another article on this site, "viewing the future of PHP from the design blueprint of Zend engine 2.0 (draft)"). For example, PHP does not have the interface concept and implementation method, and does not have any typical object-oriented features such as multi-inheritance or method overloading. If you have to adopt an object-oriented design method, it may be very easy in the outline design stage, but the detailed design stage will be quite boring. If you still have the honor to stick to the encoding stage, it is simply miserable. On the other hand, if the concept of class is not introduced in the system, but functions are used to implement module functions, you can imagine how many functions will exist in a medium or large system that adopts such "pure, the resulting troubles are obvious.

Return to the PHP language itself. Although PHP does not provide any practical object-oriented support, it still provides definitions of classes and their attributes and methods. Naturally, we can think of using the class method to encapsulate relevant function modules, which can not only draw on some advantages of Object design, but also avoid some disadvantages of fully using function modules.

(Some systems that use function modules adopt this method: Write related functions in the same file, so that they can introduce separate files during reference. For example, the member. func. php file contains all user-related operations. when processing user logon, You can first require the file and then call functions such as member_login. However, this method only solves the Code Organization Problem of many functions in the system, and does not solve the name conflict problem. As shown in the following example .)

For example, in the above User Login instance, if the function module method is used, the Code may be as follows:

The method of class encapsulation may be like this:

You may think that the code is no different (or even the code using function modules seems more concise because it does not need to get new objects ), the real difference is that it occurs in the include file. Use the function module method to organize related function sets in a file (some systems cannot do this, it will cause exceptions and chaos ), the class encapsulation method is used to declare a class with the same file name in each file (for example, in member. inc. PHP declares a member class, which is similar to Java). In use, you need to include the class first (if function modules are not well organized, some may easily include all the functions into every page. php is not compiled and executed like Java, and it takes some time to parse these functions ), but the key lies in the use of class encapsulation methods to clearly specify the location of the call-a method of a class (member) (LOGIN ): from the perspective of avoiding name conflicts, this is very successful. For code check and maintenance, the degree of convenience is self-evident. Imagine that a page needs to complete several functions, so it needs to include several files: using the function module method cannot easily find the file where the function itself is located from the function call (if there is no unified rule for the function name or include file name, so this work is very difficult), and the class encapsulation method can accurately locate the class method code location based on the class name and class file name. (You may think that such a small benefit is not enough, but after a maintenance project, there may be no objection .)

The above is the reason for adopting the class encapsulation method. It is only the first step to adopt this method to design the system. There are still many experiences to use for completing the design of the entire system.

  1. Some designs can draw on Object-Oriented ideas. Although PHP does not have an interface or abstract class definition, the inheritance mechanism is very incomplete, but at least it has a basic class definition and a simple inheritance relationship. Explicit relationships such as "company-employee" and "seller-commodity-buyer" can be easily defined by Class and Class relationships in the system. Since PHP can do this, it can be defined according to the actual logical relationship.
  2. Another problem that often occurs in the system is the relationship between individuals and lists. This may be hard to understand. Imagine the relationship between the list of posts in a BBS system and that of each post. Based on the design experience, such a relationship exists in PHP or other web systems. For this type of relationship, I personally suggest using the following item and item_list class encapsulation methods:
    • Item class definition: Code of item. Inc. php
    • Item_list class definition: Code of item_list.inc.php
  3. PHP does not have syntax access restrictions (both public) on the member variables and methods of the class, which may cause some confusion in object usage. Based on this, it is recommended that you specify in the code specifications of the development team to control this situation at the code application level:
    First, you can describe its attributes by commenting on the member variables and methods, so that other developers who use this object can understand whether their usage has violated the specified access restrictions. (If phpdoc and other automatic document generation tools are used, developers can use the class documents correctly without looking through the class source code .)
    Second, for member variable access restrictions, you can declare some major variables that often need to be accessed or changed (In comments) as public. This method saves a lot of code for get () and set () methods. Although this is considered ugly in other object-oriented languages, remember that PHP is not Java, as long as the usage is reasonable, you should use it boldly.
  4. From the above sample code, you may have noticed the proportion of comments-although everyone understands the importance of comments, it is still necessary to propose them. The javadoc style is used in this example, using existing tools can also easily generate documents directly (of course, you and your development team can also define their own appropriate annotation styles and document generation tools ). For system analysts, the code that you deliver to your development partners after the design phase is complete is probably the Framework Code that these annotations account for the majority; the tools for communication between you, except those endless charts, are the code and comments that programmers are most familiar.

Although class design in the PHP system does not require a variety of reasonable models as it is to build an object-oriented system (and there is no such "cost" for it), it still requires some consideration. Logical Rationality and operational feasibility are both the criteria for testing.

(Speaking of class design, I think of an IDE suitable for PHP development. As far as I know, Zend IDE is specialized in some Zend products. In addition, it is used as JBuilder's open tools to develop PHP tools using JBuilder; however, phped or ultraedit is the most commonly used editor. If the existing editor can be very smart to support PHP class design and code implementation, it will be very ideal .)

About View
Finally, in view, although this part of content is closely related to web designers, system analysts of PHP projects (and other web projects) must also be concerned about this topic. It can be seen that the application of MVC makes the respective work results of Web developers and program designers not affect each other as before, naturally, they can improve their work efficiency (the relationship may be more harmonious than before ). However, for system analysts, separating user interfaces into independent web templates requires a lot of analysis.

The first is to determine the entire system process, which should be done in the early stages of system design. For the view/interface and controller control/process, all required pages are generated around this process. However, what we can see in the flowchart is that the relevant parameters are transmitted between pages, but we cannot understand the content displayed on each page. This is what needs to be done in the next step to analyze the user interface.

In the analysis of the user interface, the first step is to determine the core of each page and the user interface elements (forms, form fields, links, etc.) that are essential for completing the process ); the second step is to determine the navigation content to be displayed on the page. Finally, you need to review the content based on the process. Take the above user logon as an example. For/member/login. PHP is a key page. The first step is to display a form before the user submits the page. The form contains two text boxes for the user to enter the user name and password; after submission, there is no user interface in this page according to the process. Instead, the logic layer of controller control/process is used for redirection. In the second step, you need to set the navigation link provided on the page (when the logon form is displayed accurately, here, you can add a link to the home page of the system or the start point of other non-registered user pages (to facilitate the user's temporary decision to cancel login) and a link to log out of the existing user (for logged-on users ). After review, you may find that this design does not seem to consider the better difference between Administrator Logon and common user logon before logon, then, you can add a hidden field in the form to indicate whether the user selected to Log On is prepared to log on as an administrator or a common user.

Determining the elements of the user interface does not mean that the analysis results can be delivered to the web designer; the most critical step is not to implement-create the variable names required for the template for the pages that have been analyzed. For the above User Login instances, if the system has the ability to identify users that have logged on (based on the cookie value set on the client during previous access) in addition, the user name is displayed in the user name column of the logon form. In the member_login.dwt design, the form field is assigned as a template variable (for example, {username }). After this step is completed, you can deliver it to the web designer.

It should be noted that some system designs in the encoding phase may need to be modified, which may include modifications to webpage templates, which need to be carefully processed.

Additional instructions on Code Organization
Several other files and directories are not mentioned above:

  1. Config. inc. PHP -- if you are familiar with phpMyAdmin or other projects released by phpwizard.net, you should be very clear about 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 I also advocate application in projects. In addition, to ensure conflicts with other variables in the project, we recommend that you define a multi-array in this file, and all the global variables appear with a value of this array. This makes it easier for other developers in the team to avoid using one variable name, rather than avoiding all variable names in config. Inc. php. Another benefit of using this file is that key variables (such as variables related to the server environment) are defined in a centralized manner, allowing you to easily install and transplant the entire project.
  2. Security. Inc. php-as the name suggests, this file controls and implements the security policy of the entire system. You can think of two control schemes for security: to control the current page at the top of each control flow page, and to use a control file to control the entire page, and to be added to each control flow page. I personally advocate the latter method for simple reasons: simple definition and easy maintenance. Although each page is defined separately, the efficiency may be slightly reduced (some pages that do not require security control also need to include the file for identification ), but what we get is the overall control of system security and the convenience of code maintenance (loss of an if... Else... In exchange for such a result ).
  3. /Temp -- it is obvious that all files in this directory are temporary files, and this directory does not actually appear in the official release version of the project. If you do not know how to use some functions during development or test a piece of code without relevant experience, you can create a file in this directory, because this directory is located in the project code, it can easily obtain the Context Environment for project operation, greatly reducing the cost of trial code.
  4. /Admin-the background management content of the system should be stored in an independent directory, I personally prefer the admin abbreviation (of course, in some cases, the system analyst thinks that you should not set a name that is easy to guess to manage the directory to add a heavy protection for system security ).
  5. /CSS and/scripts-both store files related to the webpage design, that is, the view/interface. They are style sheets and client scripts. The benefits of doing so will be mentioned in any book about Website planning.

Solution 2: simple website project
System performance is the primary goal of such projects. At the same time, system maintenance and expansion are almost unnecessary. (This sentence may sound a bit absolute, but determined based on the customer's needs and the nature of the project, meeting the customer's needs in the shortest possible time and making the system operate efficiently is the best test criterion for project success .) Therefore, such projects may be a paradise for PHP hackers (I used to be a person who excessively pursues PHP usage efficiency ). Due to the special nature of such projects, the scope of the discussion here is not limited to system design, but the process from the formation of a project team to the delivery of the project.

The first concern is the candidates for participating in the project (although this may be the responsibility of the Project Manager, the system analysts who are most familiar with the characteristics of the PHP project should be involved ). For PHP developers, at least developers who are familiar with various PHP functions should be selected (such projects are not suitable for developers who are involved in practical projects to train ), it would be even better if there are people in the company who can understand PHP at the source code level (but it is generally impossible for general php development companies ). In terms of web designers, it is best to select some people who have skipped the client (such as JavaScript) and the server (preferably PHP) scripts; because a major feature of such projects is that a single webpage has a large amount of code and contains webpage code (usually html), client scripts (such as JavaScript), and server scripts (such as PHP ), the purpose of adding a web designer who understands various scripting languages is not to increase the team's php development strength, but to avoid affecting the work of the program designer when modifying the web page.

The second step is process-oriented, which is precisely the page-oriented system design. Compared with the first type of project, the customer's requirements are very clear in this type of project. In addition, companies with long-term web development should also have some experience in designing such website projects. The design should focus on the entire system process, including the input parameters and output content of each page (including functional links in the webpage except navigation links), in order to fully meet the customer's needs; another key is to determine the system security policy. In such projects, the user level is determined and the page access permissions are provided, and implementation methods are provided. However, it should be noted that it is not uncommon for such projects to return the design phase from the encoding phase. Changes to local designs (such as page input parameters or output links) should be controlled in a timely manner.

Finally, we optimized the code and database. In such projects, developers should be encouraged to be hacked. The recommended solution is that the system analyst provides the pseudocode (Framework Code) for each page, while the partial implementation is performed by various program developers and web designers.

For PHP code, you can generally consider the following aspects:

  1. Algorithm selection and function implementation methods: module-level optimization can be discussed and solved by several developers;
  2. Function usage: code-level optimization requires developers to have a clear understanding of various functions and at least develop the habit of referring to the function manual;
  3. Database Query and Modification refers to the use of SQL statements: if the company has relevant database system management personnel, You can consult their suggestions on some optimization issues;
  4. Other problems that should be avoided: copying code, and other bad code situations.

According to my experience, the hacker code written in such projects is usually as follows:

  1. The use of loop statements, especially when searching: Pay attention to the difference between while and for (presumably everyone has done this kind of program in college classes), which is also a good programming habit;
  2. Optimization of SQL statements: first, avoid unnecessary database interactions as much as possible, which is very important to improve efficiency. Second, do not be afraid of statements that can be up to a few lines but prefer to use simple statements; again, we carefully consider the fields returned by the query statement to reduce unnecessary data.
  3. Obtain the submitted values of a form, such as check boxes and text fields. Exquisite form domain name design can reduce the amount of code, and you need to pay attention to the processing method when processing the submitted value.

Hacker code is encouraging in such projects, but it is best to include as detailed a comment as possible next to each piece of code.

Due to the special nature of such projects, the key to project completion is not only the system design stage, so a brief description of the process of project start, system design, coding, testing, and delivery is given:

  1. Select appropriate personnel to form a project team. You can consider adding sales personnel and customer representatives.
  2. The system analyst can summarize each page required by the system from the customer's needs and past project experience, describe its functions, and determine the initial security policy. In this step, you can add sales personnel and customer representatives. (At this time, the webpage designer is preparing to provide the customer with a series of website image pages .)
  3. In the detailed design, you need to determine the location and name of each page. More importantly, you need to determine the input parameters and output content, as well as the specific access permissions of different levels of users for the webpage. Design databases at the same time. At least the system flowchart (including access permission identification) and database design documents should be provided after this stage is completed.
  4. Webpage designers and program developers get the relevant information for their respective work. For the former, design each page based on a set of images recognized by the customer; for the latter, start coding "excited" (because the efficient introduction of Code-Hacker code is required at this time. All the difficulties encountered during this phase of work need to be reported to the system analyst. The above 3rd steps or even 2nd step-by-step design modifications may be returned.
  5. It takes some time to integrate programming and web page design. It is also the stage for developers to perform self-testing on code. At the same time, Code (including web code and program code) and database optimization can be performed at this stage. A complete system should be provided after the end of this phase.
  6. The real testing phase is usually too hasty, and companies with technology and experience in this area should also have a certain amount of experience (if there are conditions to use some software tools for stability and stress resistance testing ). Finally, a web-accessible address is provided for the customer to test. After this phase is completed, the system for formal delivery to the customer can be provided.

Solution 3: comprehensive website project
Some large websites already use PHP as the main development language. For such projects, there are not many topics worth mentioning from the PHP technology perspective. In short, it is based on the actual application of various parts of the website (access strength, operation behavior, etc) select the two proposed project design methods or use them in combination. In addition, according to my personal experience, the organization and coordination of the project team and the maintenance after the completion of each project period are more critical factors than pure technology.

For such projects, we can suggest that appropriate adoption of some open source software is good for quick and high-quality project completion. Some parts of the project can be directly introduced into the design or code of open-source software projects, but the premise is that the system designers need to be very familiar with these introduced projects, at the same time, we need to do a good job of connecting these isolated open-source projects and the entire project (such as security policy considerations and global variable references ).

For example, a comprehensive website requires the following features:

  1. Complex News Publishing;
  2. Online forums that require few management functions;
  3. Simple Product Display;
  4. User management is required.

(Obviously this is the prototype of an enterprise website .)

Among them, 1 and 2 items can obviously borrow some mature open-source software projects, and 3 items are more cost-effective due to simple independent development of customer requirements. From this point of view, four items are the most important part of the entire system-user management and integration work must be done well with 1 and 2 open source software projects (three items are integrated for independent development reasons) very simple ). (Some companies with well-accumulated technologies even have simple solutions for the integration mentioned above, so the cost for completing such a website project is very small .)

Several special features
There are also some features that usually appear in projects but must be properly handled:

1. Data list page.
There are many Chinese and English documents on the Internet about this function. The specific technology and implementation details do not need to be discussed. Here, we only need to point out the following:

A. it is recommended to encapsulate the method into a tool class or other reusable forms-the benefits are self-evident, no one wants a bunch of almost identical code as long as there is a data list page.

B. for projects with high efficiency requirements (for example, the "simple website project" type mentioned above ), you should directly use the built-in PHP operation functions for a specific database system and the result set truncation technology (SQL statements) related to the database system, such as 'limit start, offset 'in MySQL; for other projects that require system design to be well-organized (for example, the "design of a large number of business logic Projects" mentioned above), if a general database interface is used to ensure compatibility with multiple database systems, this interface can be used to filter the result set, in exchange for better maintainability and scalability of the system with a loss of efficiency. That is to say, for the use of specific database operation functions or third-party universal database interfaces to implement data list paging, the system performance and expansion should be considered.

2. Error Control.
This is also mentioned above. In addition to creating a tool-type error class, it is best to create a special error display page. This page can be a static html page (express some apologies for the user and handling instructions after the error) or a dynamic PHP page (which can contain the specific cause and location of the error and other more detailed information, provided that the information is allowed in the system security policy ). The error-type task is to accept the errors thrown by normal programs. After necessary processing, the information will be redirected together on the error display page.

At the same time, setting up an error page also has some benefits for the development phase, which can make up for the absence of try {…} similar to existing PHP {...} Catch {...} The disadvantage of block violation control is to throw and display errors or outputs in debugging through error classes.

3. upload and download.
For PHP, the upload implementation does not require the support of third-party programs as other popular web development languages. The built-in mechanism can be very simple. However, some complicated upload functions are mentioned here. Evaluate the knowledge of the next process for processing additional files:

This feature allows you to append other files when writing new messages. You can also delete or add additional files before the message is submitted. This requirement will be reflected in many office-related systems. As an experienced system analyst, we should develop implementation plans for such functions at the system design stage. For example, in the process shown in the figure, one or more forms are submitted to each other (the specific design is not described in detail, and relevant PHP file reference is provided; another intuitive example is how to add attachments to most free email systems. If you are interested, check the attachment function ).

As for downloading, placing files in the accessible directory on the Web server and providing the visitor's real file path is the simplest solution; however, in some systems, file downloading is based on some security policies that require identification before downloading. This method poses a risk. The common method may be to place files in a server file system other than the Web accessible directory or store the files in the database system. A simple program is required to obtain the file content and directly return it to the system. request user (this involves some HTTP output headers, please note, provide a PHP file instead of a specific description ). In the system design, different requirements can be adopted.

4. Session persistence
The existing PHP version has built-in support for sessions, which is usually used in projects. Some special projects (such as distribution systems) may adopt complicated processing methods.

On the client side, cookies are usually set to identify specific customers. Another way to cope with clients that do not support cookies is to use URL rewriting to add strings that are sufficient to indicate specific customers. In this regard, the PHP built-in session support is the most ideal, because it can automatically perform the fallback of the Client: if the client supports cookies, Let it go; if the cookie is not supported, use URL rewriting-no developer intervention is required. If you use other session processing methods, or write a session library that suits your needs, you need to pay attention to how to handle the client storage data-cookie or URL rewriting or both.

On the server side, simply put, you only need to store relevant data for each specific customer indicated by a string. There are various methods available, usually files and databases. In PHP's built-in session support, the default support mode is to create a file for each customer to store their data under the temporary directory of the system or a specified directory; of course, you can also modify the settings so that they support the database or other methods. If you write your own session database, select an appropriate storage method based on your system needs. It is worth noting that for distributed systems, it is of great concern to share session information on the server.

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

This is helpful for some commercial systems mentioned above: First, you can use user-related objects as a session variable value to store a set of information, rather than split Multiple Session variables. Second, if a shopping cart-like function is available, the shopping cart object can be put into the session in a way that is very consistent with the overall system design (that is, the design method of the commercial system described above, emphasizing class encapsulation.

5 ....... Other functions related to specific projects ......
It would be good to anticipate and solve these functions in the system design phase, even if a few undiscovered features are left in the coding stage, it is not terrible-such omissions do not affect the entire system architecture, you only need to return to the design stage and add the corresponding content and documents. After all, it is unrealistic for system analysts who have little experience in related projects to understand such functions at the design stage.

About Other
There have been a lot of arguments about PhP in the past, but since Java's advantages in the Web field have increasingly entered people's field of view, this debate has been exhausted-it seems that everyone has reached a consensus-PHP is still powerless for rigorous commercial systems. However, it is not objective to simply deny the application of PHP in commercial systems. After all, PHP also has a low-cost advantage (the cost here includes development cost, use cost and maintenance cost ). The purpose of this article is not only to introduce some PHP system design methods, but also to attract some developers or enterprises to use PHP to build suitable commercial systems.

In addition, this article is just some of my own experience. If you have some ideas here, I would like to share with you that it is very exciting to be able to promote the development of open-source software without commercial support such as PHP. (In this regard, I even want to write documents and demonstration projects on PHP development, just like the blueprint and Java pet store released by Sun Microsystems for J2EE-unfortunately, time, energy, and personal capabilities are temporarily limited-maybe the Spring Festival holiday is a good time :)

References

  • Articles and Code mentioned in this Article
    • Code: User logon to the instance (including control page index. php, login. php; webpage template member_index.dwt, member_login.dwt; logical class member. Inc. php) related attachments;
    • Code: Class encapsulation instance (the item class defines item. Inc. php; The item_list class defines item_list.inc.php) related attachments;
    • Code: Upload the attachment of an instance (Add. php, attach. php on the control page;
    • Code: Download the attachment related to the instance (control page download. php;
    • Code: two global files (config. Inc. php, security. Inc. php) in the instance code organization;
    • Article: The Future of PHP;
    • Article: Use of templates in PHP.
  • Other references
    • PHP official website-http://www.php.net
      Including software and documentation and usage (the latest trend in this article is the release of PHP 4.1.0, which has greatly improved in some aspects ).
    • Http://www.zend.com, A Zend company that provides commercial support for PHP
      Includes PHP-related tools and text materials (you can find some topics related to this topic ).
    • Http://www.sourceforge.net, soureforge, a well-known open source project website
      A collection of open source projects and various web-based convenience tools (you can find thousands of PHP 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: 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.