PHP code design structure

Source: Internet
Author: User
Tags strtok
Welcome to the Linux community forum and interact with 2 million technical staff for many years. coding has been around for various codes day and night. How to get along with code is not only a response in your career, it is also a direct manifestation of the writer's skill. What do you think of programs and code? Let's start with the definition of the program. If we look at the final presentation of the business

Welcome to the Linux community forum and interact with 2 million technical staff> after coding for many years, various codes are accompanied by day and night. How to get along with codes is not only a kind of response in your career, it is also a direct manifestation of the writer's skill. What do you think of programs and code? Let's start with the definition of the program. If we look at the final presentation of the business






Welcome to the Linux community forum and interact with 2 million technicians>

Coding has been around with various codes for many years. How to get along with codes is not only a kind of response in your career, but also a direct reflection of the writing skills.

What do you think of programs and code?

Let's start with the program definition,

If we look at the final presentation of the business, a program can be considered as a logical code ing for real business needs.

From the logic structure of the program, the program combines the data structure with the algorithm.

In this way, more program code is needed to meet more business needs and better meet these needs,

After the program code accumulation reaches a certain number, it is important to manage and sort out the existing code. This is also a programmer programming 3 ~ 5, from the intermediate level to a higher level of exploration bottleneck.

It is better to meet the code that needs to work. It can be reused by multiple requirements.

With the development of software design, the collection of code, and the gradual accumulation of functional logic, the trend of encapsulation becomes increasingly clear.

Using a good tool quickly requires constant attempts and improvements to master a design idea.

There are code that specifically process data and code that specifically process rendering. How can I manage and configure them in a business flow? How can these logics be better encapsulated and reused.

In fact, for PHPer, these ideas are a little troublesome in dealing with specific businesses. This is also the biggest advantage of PHP, which is very convenient and basic syntax, you can easily connect to memory resources without considering it. Soon you can get a hello,

However, this is also a major disadvantage inherent in PHP. It does not have a systematic design system,

PHP was born with a single language that satisfies the business and does not have a very systematic design system and principles like JAVA. There are three basic design principles in JAVA: 1. Global variables are not supported. 2. Do not write omnipotent classes. 3. The code must be class encapsulation.

The first and third principles of JAVA are limited in syntax. The second principle is to judge whether a JAVA programmer is getting started. PHP has almost no syntax limitations, but some big companies have no system principles,

But in our design philosophy, we cannot really have no principles!

PHP programs are actually easy to use. The interpreter is very powerful and can block program code that embraces various ideas. As long as the syntax is OK, you don't care about code design.

Because PHP was too casual in the early days, it was easy to get started, and it was not necessary to effectively manage and reuse the code.

With the development of PHP, PHP has already said goodbye in PHP3 ~ Dynamic markup language in the PHP4 era, but due to the upward compatibility principle, PHP is still a language with loose syntax,

Systematic Program Design Principles have not yet been forcibly integrated into the language core.

This does not mean that we do not need to use mature design ideas to improve and compile our program code.

JAVA programming principles and code accumulation are the essence of JAVA, and become more and more obvious over time.

Introduce JAVA programming ideas into the PHP programming process. Is a good way to improve PHP code.

1. Hierarchical code Encapsulation

2. Flexible file calling and loading, and Resource Creation upon use

3. Smooth and anti-aging directory structure

Solving these problems can bring a lot of benefits to the programming process.

How can this problem be solved?

Through the dismantling and encapsulation of MVC design ideas, we can achieve a clear, effective, and consistent program design idea.

A program can be viewed as Model, View, and Controller logical blocks in the logical structure.

In JAVA, the Model layer implements the business logic in the system, which can usually be implemented using a JavaBean or EJB. The View layer is used for interaction with users. It is usually implemented using JSP. The Controller layer serves as a bridge between the Model and View. Generally, the router servlet extends to the application end.

But PHP does not have such a clear division, so we need to incorporate the design idea into the program code.

1. program code Encapsulation

For an application requirement (ex: similar product page), the requirement is divided into three files: similar. controller. php; similar. model. php. similar. view. through the php name, we can also see the code usage in each file. The rest is to name the classes in each file.

Because it is different operation classes for an application, you need to add different category suffixes to each category,

For example, similar. controller. php1 2 3 4 5 6 7 8 9 10 11 // The controller control program class completes the process on each page of the program, each method corresponds to a synchronous request page (to comply with the call rules of the page)

Class similar {// display functio do_opensearch ($ _ param) on the similar product page) {// request parameter filtering // Request Product Data // process product data according to the rendering rules // render product data to get rendered html // display rendered html}

The corresponding request is

Http://s.etao.com/similar/opensearch/

Similar. model. php

 // The model data operator class encapsulates the data request for this application, and the structure parsing of the returned results processes class similarmODEL {}

Similar. view. php

// model presents the program class to encapsulate the data of this application, and returns it to the processed class similarVIEW {function view_getDetail ($ _ goodDataArr) {return $ html ;}

2. Class call

We clearly encapsulate different codes in different files and classes. How can we make flexible calls? PHP is an interpreted language. It does not have a compilation process like JAVA and C. It cannot enjoy the compilation language and is automatically connected during the pre-compilation process.

In fact, the PHP interpreter is aware of this problem and has proposed the autoload method after 5.3.1, when the interpreter encounters a non-declared class or function, it will automatically run autoload to load it again. If no error is reported.

For more information, see http://php.net/manual/en/language.oop5.autoload.php

However, this is a passive solution. The following provides an active and dynamic loading solution. Before adding the resource system transfer class, let's take a look at the process of loading and using a class file: similar. controller. php.

 require_once PATH. "similar. model. php"; $ sModelObj = new similarmODEL; $ goodsData = $ sModelObj-> getGoodsInfoByNid ($ nid );

This is called in the process. If it is called in the controller class, you need to write it like this,

 require_once PATH. "similar. model. php "; class similar {public $ _ modelObj; function _ construct () {$ this-> _ modelObj = new similarmODEL ;} // show the similar product page functio do_opensearch ($ _ param) {// Request Product Data $ goodsInfoArr = $ this-> _ modelObj-> getGoodsInfoByNid ($ nid );}} // end class

If the controller class needs to use another MODEL, such as forest and ha3, it is necessary to declare element variables in multiple classes. Using the variable transmission feature of PHP, it is much easier to create a resource scheduling class to uniformly load and declare the classes required for scheduling. Next we will detail the design of this resource scheduling class,

/*** load a specified type of class program **/class Box {// declare a pool of In-process resource objects public static $ _ modelObjArr; // obtain a resource object public static function getObj ($ _ appName, $ _ typeStr = 'class '){

If ($ _ typeStr = 'class') {$ className = $ _ appName;} else {$ className = $ _ appName. strtoupper ($ _ typeStr);} // if (isset (self: $ _ modelObjArr [$ className]) & is_object (self :: $ _ modelObjArr [$ className]) {return self: $ _ modelObjArr [$ className;} // load a file resource class FILE $ file = dirname (_ FILE __). "{$ _ AppName}/{$ _ appName }. {$ _ typeStr }. php "; if (file_exists ($ file) {require_once $ file; if (class_exists ($ className) {return self: _ createObj ($ className );} else {$ errStr = "no class {$ className} in file {$ file }"; // class name error} else {$ errStr = "no class file {$ file}"; // class file error} self ::_ showErr ($ errStr );} // create a resource object public static function _ createObj ($ _ className) {if (isset (self ::$ _ modelObjArr [$ _ className]) & is_object (self :: $ _ modelObjArr [$ _ className]) {return self ::: _ modelObjArr [$ _ className];} else {self :: $ _ modelObjArr [$ _ className] = new $ _ className (); return self: $ _ modelObjArr [$ _ className];} // public static function _ showErr ($ _ errTypeStr = '') {echo $ _ errTypeStr; exit; // errorlog ($ _ errTypeStr);} // end class

Use the Box resource scheduling class to load the class program file: similar. controller. php.

 class similar {

Function _ construct () {}// display of similar product pages functio do_opensearch ($ _ param) {// Request Product Data $ goodsInfoArr = Box: getObj ('similar ', 'model')-> getGoodsInfoByNid ($ nid); $ html = Box: getObj ('similar ', 'view')-> view_getDetail ($ goodsInfoArr ); // other encapsulated data logic $ hotHtml = $ this-> _ getHotHtml ();} function do_search ($ _ param) {$ goodsInfoArr = Box :: getObj ('similar ', 'model')-> getGoodsInfoByNid ($ nid); $ html = Box: getObj ('similar', 'view ') -> view_getDetail ($ goodsInfoArr);} function _ getHotHtml () {$ hotInfoArr = Box: getObj ('similar ', 'model')-> getGoodsInfoByNid ($ nid ); $ html = Box: getObj ('similar ', 'view')-> view_getDetail ($ goodsInfoArr); return $ hotInfoArr;} // end class

In this way, the "similar. model. php" file in a response process will be loaded only once, and the similarmODEL will be created only once and called as needed. You do not need to declare it in advance. You do not need to consider duplicate loading or duplicate creation.

Box solves the call and creation of resources between classes.

So how to run the function in a controller file? We need a request scheduling class Bin.

Previously, our request response city was completed through the I/O model of websearch. The Request path is mapped to the actual file.

For example: xxxx.taobao.com/similar/opensearch/index.php or xxx.etao.com/similar/opensearch.php, websearch replaces the host with the path of the actual file system.

In this way, external programs can scan our directories, and some common methods will be exposed if they are neglected. ex: xxxx.taobao.com/tools/info.php or something poses a risk.

Of course, adding some filter conditions can block such problems, but it will increase or decrease the logic of webserver. Once modified, it will change the conf of webserver. Simply put, we will pack and unpack the I/O and http on the webserver,

Let the app server filter and flexibly configure request calls. Then, all access requests are mapped (rewitre) to the host/dispatch. php In the webserver, Which is scheduled and allocated by the Bin Class. Implement the single-entry call structure of application logic.

Dispatch. php provides platform-level functions such as platform allocation, performance monitoring, configuration loading, application startup, and type-based input (synchronous, asynchronous, PC, and mobile.

The Bin Class requires the following functions: parse the request, pass the environment variables passed by webserver to the actual processing application of the response to complete the decomposition, and propose the similar application name and opensearch method name,

Also, GET and POST request parameters are assembled into an array of request parameters,

 $ this-> _ paramArr = explode ('/', trim (strtok (urldecode ($ _ SERVER ["REQUEST_URI"]), '? '),'/'); $ This-> _ paramArr = array_merge ($ this-> _ paramArr, $ _ GET );

In this way, $ this-> _ paramArr [0] is the appname Application name. $ this-> _ paramArr [1] is the function method name.

The platform flow can load the appname. class. php file and execute the appname-> do_function ($ this-> _ paramArr); method.

This also supports passing parameters such as/similar/opensearch/sort/. sort is a parameter of $ this-> _ paramArr [2 ].

If $ this-> _ paramArr [0] is equal to ajax, this is an asynchronous request initiated by js,

Appname. ajax. php is to be loaded, and appnameAJAX-> ajax_function () is executed ();

Split the synchronous and asynchronous requests into files. Reduce the memory usage for loading large files.

In addition, the accessible directories and application directories can be physically classified to make scanning programs useless.

For example:

/Home/website/host/This directory only contains one index. php file, and some rendering files that are not added to cdn, such as css, js, and images. Set docmentroot or laction of webserver to the/home/website/app/directory to store the written class program file. The configuration is set by/host/index. php programs load class program files under the app directory

One application is easy to handle. What should we do with a bunch of applications? The following describes the directory structure of multiple applications.

3. directory structure (anti-aging is important)

The design concept of PHP is rare, and there is no concept of a package. We had to use the directory to package the concept. Describes the functions of the directory structure from the access structure, development structure, and deployment structure.

3a. The access structure regards the access directory host and the application directory app as a website, and the applications under this site can

You can create/website/host/website/app/similaer/website/app/cmp/website/app/srp/website/app /.........

If the management tool can also create a directory/website/admin/firebox/website/admin/seoAny at the same website, all requests will go to/website/host/index. php by index. php loads the response logic program according to the request rules.

There is a system directory in parallel with/webiste/host,/website/system. class. php, bin. class. php, base. class. php and other platform files are stored.

The execution process of a response is webserver query-> [/website/host/index. php include/website/system/box, bin, base (application architecture)] platform-> [/website/app/(application process) |/website/admin/] Page

3b. during Development and Maintenance of the development structure, there will be some php library files, such as curl communication, xml parsing, log, timer, template (appview), and other self-developed class programs, there are also third-party class libraries such as smarty and big2gb.

All projects are universal, price comparison, primary search, my yitao, then you can create a PHPLIBS directory at the same level as website/host/website/app/website/system/PHPlibs/etao/your own class library/PHPlibs/other/third party. class Library

Each website has a svn PHPlibs/an independent svn dedicated person for maintenance.

Separate the template file from website/and create a webtemplate/directory to share the svn with the ued students so that the ued students can write the template file according to the previous template class rules. Store data by application directory.

For example: webtemplate/srp webtemplate/cmp webtemplate/opensearch webtemplate/frame uniform rendering template, webtemplate/at the beginning and end of the page /.........

Website/app programs use the template class method to call the above template file.

At the same time, you will also encounter php scripts that require shell execution during development and maintenance, such as regularly generating public headers and tails, and regularly obtaining the epid data in the mysql database. Or temporarily create an algorithm program.

Then we can add an app to the/website/app/related applications. sh. php program files, such as/website/app/similar. sh. similarSH of the php file is passed through/website/script/run. php. Script/run. php is a shell controller that responds to CLI requests, host/index. php is a web controller that can respond to CGI requests in script/run. php package a debug. bat files can already be in dos or packaged with a debug. THE sh program then directly performs interactive debugging under shell.

Reference Code

There are also some programs that process files, such as the Public header and tail files of php templates converted from vm files, there will be a webdata file parallel to website,/website /....

/Webdata/pageframe and other directories, directly called in the app

3c. The deployment structure is checkout/website/PHPlibs // webtemplate/svn resource library through the launch script.

Then Package the rpm and push it online.

Independently launch the product by using the launch script configuration to check the corresponding files and push them to the previous production machine.

4. Code specifications

We have been discussing code format standards for a long time.

The code format is standardized. We can configure it in IDE for automatic use, and cultivate the habit of writing easy-to-read code through constant review and reminders.

The code design specification must be specified according to the architecture and be executed persistently.

The code design is based on the resource calling and request allocation mentioned above.

4a, about the directory // application/website/app /....

// External access directory/website/host/index. php/website/host/css/website/host/js/website/host/images // Platform System File/website/host/images // debug, maintain the script/website/script // The directory/webtemplate/… corresponding to the/website/app/template library /....

// Program class library/PHPlibs // data file directory/webdata

There is nothing to say.

4b. The naming rules for file files mainly include specifying internal calls and requesting website/app/appname calls. apptype. php apptype: class, model, view, ajax, api, sh ,....

Call: Box: getObj (appname, apptype)-> function ();

The appname. class. php file is the controller file, and the methods in the class perform synchronous request response.

The appname. ajax. php file is also a controller file, and the method in the class performs asynchronous request response.

The appname. sh. php file is also the controller file, and the method in the class performs CLI response.

The appname. api. php file can be viewed as a controller file. The methods in the class are encapsulated in a public or general logic, such as obtaining the complete path of an image.

4c. class and method class naming: Except for the class file, the appname is used directly. All other class files are named by appname + APPTYPE, and APPTYPE must be capitalized. Better syntax differentiation.

Method Name: Add a prefix to the method declaration to describe the role of the method. For example, add html_getSimilarList () to the method in the view class, and add db_getData () to the model method to obtain the data from the database. file_getData () get from file, url_getData () Get from engine or remote

4d: for variables and comments, the parameter entry variable is prefixed with _, which is distinguished from the local variables used in the process to improve readability.

 class similar {public $ _ obj; function do_getpage ($ _ param ){}

File annotation = Class annotation is added at the beginning of the file to describe the functions of this class:/*** @ package: * @ access: MixrenSystemBox. inc. php * Summary: The System Application Template controls the allocation program; completes request analysis; Module loading; Request Processing (execution); * @ Created: Fri Dec 25 16:41:02 CST 2009 * @ Author: zhurong * @ Generator: EditPlus2 & Dreamweaver & Zend & eclipse */

Method annotation/*** initialize request ** param parameter description **/private function _ parseApp () {$ this-> _ queryStr = urldecode ($ _ SERVER ["REQUEST_URI"]); $ this-> _ paramArr = explode ('/', trim (strtok ($ this-> _ queryStr ,'? '),'/'); // Allocation request module $ appName = DEFAULT_APP_NAME; $ this-> _ className = $ appName; $ this-> _ appFile = APP_PATH. "{$ appName}/{$ appName }. controller. php "; $ this-> _ method = empty ($ this-> _ paramArr [0])? DEFAULT_APP_METHOD: $ this-> _ paramArr [0]; $ this-> _ method = "do _ {$ this-> _ method }";}

Class Bin {}// end class

As the main process and algorithm, add comments to facilitate maintenance and reading.

Before going online, php-w will be used to annotate the file through the launch script. Therefore, the duration of annotation writing does not occupy the memory loaded during program execution.

5. Code monitoring

Dedicated code scanning scripts.

Scan directories, files, methods, and comments in/website/app.

Output reports, application directories, Synchronous Response classes, asynchronous response classes, synchronous pages, asynchronous interfaces, logical interfaces, model interfaces, and templates; the code comment rate of each file, and so on.

Based on the above design ideas, a tree structure design program architecture is established from the folder-> segmented files-> functional module methods to maximize the consistency (consistency) and availability (reusable) of the CAP principle ), partition (effective Division)

Make PHP code better accumulate.

Template (pure html file, rendering configuration), the Program Data configuration file is loaded into the program, rather than loading the program into the html section to explain and execute.


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.