PHP Best Practices

Source: Internet
Author: User
This afternoon, I am reading the following article. Although the name is "PHP best practices", it focuses not on programming rules, but on the rational architecture of PHP applications. It provides an architecture mode for logical and data separation and is a practice of the MVC mode. I think this is a useful learning material. There are not many similar articles on the Internet.

This afternoon, I am reading the following article. Although the name is "PHP best practices", it focuses not on programming rules, but on the rational architecture of PHP applications. It provides an architecture mode for logical and data separation and is a practice of the MVC mode. I think this is a useful learning material. There are not many similar articles on the Internet.

This afternoon, I am reading the following article.

Although the name is "PHP best practices", it focuses not on programming rules, but on the rational architecture of PHP applications.

It provides an architecture mode for logical and data separation and is a practice of the MVC mode. I think this is a very useful learning material. There are not many similar articles online, so I translated it as I learned it.

Based on my understanding, I have summarized the implementation of its MVC mode (for details, see the translation ):

*View): Front-end webpage;

*Logic layer (Controller): Page Controller processes Page requests. Then, it calls Business Controller to implement specific functions;

*Data Layer (Model): Data is stored in the database. There is a database abstraction layer on top, and a "Data Access Object" (DAO) is created to generate a "Value Object ). The business logic uses DAO to operate value objects.

========================================================

  PHP Best Practices

Original: http://www.odi.ch/prog/design/php/guide.php

Translator: Ruan Yifeng

This article provides solutions to common PHP programming problems and briefly describes the PHP application architecture.

  1. php. ini settings

Php. ini controls the interpreter's behavior. The following settings ensure maximum portability of your program.

I. short_open_tag

Ii. asp_tags

Iii. magic_quotes_gpc

We recommend that you include a global file in the script. before reading the $ _ GET, $ _ POST, and $ _ COOKIE variables, check whether the setting is enabled. If yes, this applies the stripslashes function to these variables. (Note: This setting has been abolished in PHP 5.3 .)

Iv. register_globals

Do not rely on this setting. Always use the global variables $ _ GET, $ _ POST, and $ _ COOKIE to read GET, POST, and COOKIE values. For convenience, we recommend that you declare $ PHP_SELF = $ _ SERVER ['php _ SELF '].

V. file_uploads

The maximum size of the uploaded file is determined by the following settings:

* File_uploads must be set to 1 (default) to allow upload.

* Memory_limit must be slightly larger than post_max_size and upload_max_filesize.

* Post_max_size and upload_max_filesize must be large enough to meet the upload needs.

  2. configuration file)

You should write all the configurations related to the application in a file. In this way, you can easily adapt to the changes in the development environment. The configuration file usually contains the following information: Database parameters, email addresses, various options, debug and logging Output switches, and application constants.

  3. namespace)

When selecting the class and function name, you must be careful to avoid duplicate names. Do not place global functions outside the class as much as possible. Internal Attributes and methods of the class are protected by namespaces. If you do need to declare global functions, use a prefix, such as dao_factory (), db_getConnection (), text_parseDate (), and so on.

  4. Database abstraction layer

PHP does not provide common functions for database operations. Each database has its own function. You should not directly use these functions. Otherwise, once you switch to another database (for example, from MySQL to Oracle), you will have a lot of trouble. In addition, the database abstraction layer is generally easier to use than the database functions of the system.

  5. "Value Object" (VO)

The value object (VO) is in the form, just like the struct structure in C language. It is a class that only contains attributes and does not contain any methods (or contains only a few methods. A value object corresponds to an object. Its Attribute should be the same as the field name of the database. In addition, there should be an ID attribute.

Class Person {

Var $ id, $ first_name, $ last_name, $ email;

}

  6. Data Access Object (DAO)

The role of a Data Access Object (DAO) is to isolate database access from other code. DAO should be stacked, which will help you add database cache in the future. Classes of each value object should have their own DAO.

Class PersonDAO {
Var $ conn;

Function PersonDAO (& $ conn ){
$ This-> conn = & $ conn;
}

Function save (& $ vo ){
If ($ v-> id = 0 ){
$ This-> insert ($ vo );
} Else {
$ This-> update ($ vo );
}
}

Function get ($ id ){
# Execute select statement
# Create new vo and call getFromResult
# Return vo
}

Function delete (& $ vo ){
# Execute delete statement
# Set id on vo to 0
}

# -- Private functions

Function getFromResult (& vo, $ result ){
# Fill vo from the database result set
}

Function update (& $ vo ){
# Execute update statement here
}

Function insert (& $ vo ){
# Generate id (from Oracle sequence or automatically)
# Insert record into db
# Set id on vo
}
}

DAO should usually deploy the following methods:

* Save: insert or update a record.
* Get: retrieve a record.
* Delete: delete a record.

You can add other DAO methods as needed. Common examples include isUsed (), getTop ($ n), and find ($ criteria ).

However, all DAO methods should be related to database operations, and no other operations should be performed. DAO should only perform basic select/insert/update operations on a table, and should not contain business logic. For example, PersonDAO should not contain the code for sending emails to someone.

You can write a factory function and return the corresponding DAO according to different class names.

Function dao_getDAO ($ vo_class ){

$ Conn = db_conn ('default'); # get a connection from the pool

Switch ($ vo_class ){

Case "person": return new PersonDAO ($ conn );

Case "newsletter": return new NewsletterDAO ($ conn );

...

}

}

  7. automatically generate code

99% of the value object and DAO code can be automatically generated according to the database schema, provided that your tables and columns are named in the agreed manner. If you modify the database mode, a script that automatically generates code will greatly save you time.

  8. Business Logic

Business Logic directly reflects users' needs. They process value objects, modify the properties of value Objects Based on business needs, and use DAO to interact with the database layer.

Class NewsletterLogic {
Function NewsletterLogic (){
...
}

Function subscribePerson (& $ person ){
...
}

Function unsubscribePerson (& $ person ){
...
}

Function sendNewsletter (& $ newsletter ){
...
}
}

  9. Page logic (Controller)

When a webpage is requested, the page controller runs and generates output. The Controller's task is to convert an HTTP request into a business object, and then call the corresponding business logic to generate an object that displays the output.

The page logic is followed by the following steps (refer to the code of the PageController class ):

I. Assume that the page request contains a cmd parameter.

Ii. Execute the corresponding action based on the value of the cmd parameter.

Iii. Verify the value returned on the page and generate a value object.

Iv. perform business logic for value objects.

V. If necessary, you can direct to another page.

Vi. Collect necessary data and output results.

Note: you can write a utility function to process GET or POST values. When some variables are not assigned a value, a default value is provided. The page logic does not contain HTML code.

Class PageController {
Var $ person; # $ person is used by the HTML page
Var $ errs;

Function PageController (){
$ Action = Form: getParameter ('cmd ');
$ This-> person = new Person ();
$ This-> errs = array ();

If ($ action = 'save '){
$ This-> parseForm ();
If (! This-> validate () return;

NewsletterLogic: subscribe ($ this-> person );

Header ('location: confirmation. php ');
Exit;
}
}

Function parseForm (){
$ This-> person-> name = Form: getParameter ('name ');
$ This-> person-> birthdate = Util: parseDate (Form: getParameter ('birthdate ');
...
}

Function validate (){
If ($ this-> person-> name = '') $ this-> errs ['name'] = FORM_MISSING;
# FORM_MISSING is a constant
...
Return (sizeof ($ this-> errs) = 0 );
}
}

  10. Presentation Layer)

The top-level page contains the actual HTML code. All business objects required for this page are provided by the page logic.

This page first reads the properties of business objects and converts them to HTML format.

Require_once ('control/ctl_person.inc.php '); # the page controller
$ C = & new PageController ();
?>


  
  
  
  

  11. Localization)

Localization means to support multiple languages. This is troublesome. You can choose either of the following two methods:

A) prepare multiple pages.

B) Remove the content related to a specific language from the HTML page.

Generally, method A is used more often, because Method B makes the HTML page less readable.

Therefore, you can write the pages of a language first, then copy them, and use a naming method to differentiate the versions of different languages. For example, index_fr.php indicates the French version of index. php.

You can use the following methods to save your language selection:

A) Save the language settings in A session variable or cookie;

B) read the locale value from the HTTP header;

C) append the language setting to each URL as a parameter.

It seems that method A is much easier than method C (although the session and cookie both have an expiration issue), and method B can only be used as A supplement to method A or method C.

Finally, do not forget that fields in the database must also be localized.

  12. installation location

Sometimes you need to know where the ROOT directory of the program is, but $ _ SERVER ['document _ root'] is only the ROOT directory of the web SERVER, PHP cannot automatically know if your program is installed in a subdirectory of it.

You can define a global variable $ ROOT, whose value is the ROOT directory of the program, and then include it in every script file. Then, you need to include a file and write require_once ("$ ROOT/lib/base. inc. php ");.

  13. directory structure

First, each class should have its own independent file, and it must have a set of naming rules for file names (naming convention ).

The directory structure of the software can be as follows:

/Root directory. The browser starts to access this page.

/Lib/contains global variables (base. inc. php) and configuration files (config. inc. php ).

/Lib/common/libraries that can be shared by other projects, such as the database abstraction layer.

/Lib/model/contains value object class.

/Lib/dao/contains the data access object (DAO) class and DAO factory functions.

/Lib/logic/contains the business logic class.

/Parts/contains HTML template files.

/Control/contains page logic. For large programs, there may be sub-directories (such as admin/AND/pub/) under this directory /).

In the base. inc. php file, add the include files in the following order:

* Classes frequently used in/lib/common (such as the database layer ).

* Configuration file;

* All classes in/lib/model;

* All classes in/lib/dao.

The directories that store images and upload files are omitted here.

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.