Use PEAR to write your PHP program and read PEAR to write your PHP program. as mentioned above, PEAR manages the PEAR application code library according to certain categories, your PEAR code can be organized into the appropriate directory, and others can easily retrieve and share your results. PEAR is not only a code repository, but also a standard. it is used to "> <LINKhref =" http: // ww
As mentioned above, PEAR manages the PEAR application code library according to certain categories. your PEAR code can be organized into appropriate directories, others can easily retrieve and share your results. PEAR is not only a code repository, but also a standard. Using this standard to write your PHP code will enhance the readability and reusability of your program and reduce the chance of errors. PEAR builds a framework for you by providing two classes to implement functions such as destructor and error capture. you can use these functions through inheritance.
PEAR encoding rules include indentation rules, control structures, function calls, function definitions, comments, including code, PHP tags, file header comments, CVS tags, and URL samples, constant naming. The following is a brief introduction:
Indent rules:
In PEAR, four spaces are required for code reduction, and TAB is not used. If you use VIM, put the following settings into your ~ /. In vimrc: set expandtab
Set shiftwidth = 4
Set tabstop = 4
If you use Emacs/XEmacs, set indent-tabs-mode to nil.
But you like to use (X) Emacs to edit php files like me, I strongly recommend you install PHP-MODE so that when you write PEAR code, it will automatically adjust your shrink style, of course PHP-MODE has many excellent features that you can download the latest PHP-MODE from the list of resources.
Control structure:
The control structure mentioned here includes: if for while switch. For control structures, in keywords (such as if ..) leave a space box and then use parentheses to avoid confusion with function calls. In addition, you should try to use curly braces {} as far as possible {}, even if the syntax is optional. In this way, you can avoid logical doubts or errors when adding new code lines. Here is an example: if (condition 1) & (condition 2 )){
Statement 1;
} Esleif (condition 3) | (condition 4 )){
Statement 2;
} Else {
Statement 3;
}
Function call:
For function calling, the function name and left parenthesis (there should be no space between them. for function parameters, there must be the same space separation between the separated comma and the next parameter, there must be no space between the last parameter and the right brace. The following is a standard function call; $ result = foo ($ param1, $ param2, $ param3 );
Non-standard writing:
$ Result = foo ($ param1, $ param2, $ param3 );
$ Result = foo ($ param1, $ param2, $ param3 );
In addition, if you want to assign values to the results returned by the function, there must be spaces between the equal sign and the assigned variable. In addition, if you are using a series of related values, you should add appropriate spaces, align them like this: $ result1 = $ foo ($ param1, $ param2, $ param3 );
$ Var2 = $ foo ($ param3 );
$ Var3 = $ foo ($ param4, $ param5 );
Function definition:
Function definition follows the "one true brace" convention: function connect (& $ dsn, $ persistent = false ){
If (is_array ($ dsn )){
$ Dsninfo = & dsn;
} Else {
$ Dsninfo = DB: parseDSN ($ dsn );
}
If (! $ Dsninfo |! $ Dsninfo ['phptype ']) {
Return $ this-> raiseError ();
}
Return true;
}
As shown above, optional parameters must be at the end of the parameter table and always return meaningful function values whenever possible.
Notes:
Online documents of classes should be converted to PHPDoc, just like JavaDoc. PHPDoc is also an application of PEAR, more detailed introduction you can go to http://www.phpdoc.de/view. In addition to the online documentation of classes, we recommend that you use non-document comments to interpret your code. when you see a piece of code, consider: Oh, I don't need to describe it carefully in the document. So you 'd better make a simple comment on the code to prevent you from forgetting how it works. For the form of annotation, C's/**/and C ++'s // are both good. however, do not use Perl or shell's # annotation method.
Code included:
Whenever you need to include a class file unconditionally, you must use requre_once; when you need to include a class file, you must use include_once; this ensures that the files you want to include will only be contained once, and the two statements share the same file list, so you do not have to worry about confusion between the two statements. once require_once contains a file, include_once will no longer contain the same file, and vice versa.
PHP code tag:
Define your php code at any time, instead of simply using it. this ensures PEAR compatibility and facilitates cross-platform porting.
Annotation declaration of the file header:
All PHP code files that need to be included in the PEAR core release. at the beginning of the file, you must add the following comments:/* vim: set expandtab tabstop = 4 shiftwidth = 4: */
// + ------------------------------------------------------------------------ +
// | PHP version 4.0 |
// + ------------------------------------------------------------------------ +
// | Copyright (c) 1997,199 8, 1999,200 0, 2001 The PHP Group |
// + ------------------------------------------------------------------------ +
// | This source file is subject to version 2.0 of the PHP license, |
// | That is bundled with this package in the file LICENSE, and is |
// | Available at through the world-wide-web at |
// | Http://www.php.net/license/2_02.txt. |
// | If you did not receive a copy of the PHP license and are unable to |
// | Obtain it through the world-wide-web, please send a note to |
// License@php.net so we can mail you a copy immediately. |
// + ------------------------------------------------------------------------ +
// | Authors: Original Author |
// | Your Name |
// + ------------------------------------------------------------------------ +
//
// $ Id $
For files not in the PEAR core code library, we recommend that you have such a comment block at the beginning of the file to indicate copyright, protocol, author, and so on. At the same time, we also add the vim modeline in the first line, so that we can maintain the PEAR code style in VIM.
CVS flag:
As shown above, add the cvs id tag to each file. if this tag is not found in the edited or modified file, add it, or replace similar representations in the original file (such as "Last modified)
URL sample:
You can refer to RFC 2606 and use "www.example.com" as all URL samples.
Constant name:
Constants should be capitalized as much as possible. to facilitate understanding, use underscores to separate each word. At the same time, you should use the package name or class name where the constant is located as the prefix. For example, constants in the Bug class should start with Bug. The above are PEAR encoding rules. for detailed encoding rules, refer to the description of CODING_STANDDARD file in PEAR. To better understand these encoding rules, you can also refer to the code of the existing PEAR core module.
Start using PEAR
It's easy to use PEAR. you just need to define your own PEAR program: require_once "PEAR. php ";
Class your_class_name extends PEAR {
Your class definition...
}
Of course, you need to follow the PEAR encoding rules mentioned above, and then you can implement what you want to do inside your class. Next, let's discuss it. In fact, PEAR provides us with two pre-defined classes: PEAR: this is the base class of PEAR. all PEAR extensions must be derived from it. PEAR_Error: base class for processing PEAR errors. you can choose to derive your own error processing class.
Generally, you should not directly create a PEAR instance, but instead derive a new class and then create an instance of the new class. As a base class, PEAR provides us with some useful functions, mainly including destructor and error handling.
Destructor
PHP supports constructor, but does not support destructor. However, PHP provides the register_shutdown_function () function, which can call back the registered function before the script ends. Therefore, PEAR uses this feature, simulation of destructor is provided. If you have a PEAR subclass called mypear, you can define a function in the mypear class. the function name is underlined and your class name, _ mypear (), this function is the destructor of this class. However, this destructor is not the same as the Destructor in C ++. it will not be executed when the object is deleted, but at the end of the script. after all, this is just a simulation. Since register_shutdown_function () is used, the printed information in your destructor will not be returned to the browser. In addition, you need to call the constructor of its parent class in your constructor, because PHP will not automatically call the constructor of the parent class, the Destructor needs to be registered in the PEAR constructor. let's take a look at the source code of PEAR: function PEAR (){
If (method_exists ($ this, "_". get_class ($ this ))){
Global $ _ PEAR_destructor_object_list;
$ _ PEAR_destructor_object_list [] = & this;
}
If ($ this-> _ debug ){
Printf ("PEAR constructor called, class = % s \ n ",
Get_class ($ this ));
}
.....
Function _ PEAR_call_destructors (){
Global $ _ PEAR_destructor_object_list;
If (is_array ($ _ PEAR_destructor_object_list) & sizeof ($ _ PEAR_destructor_object_list )){
Reset ($ _ PEAR_destructor_object_list );
While (list ($ k, $ objref) = each ($ _ PEAR_destructor_object_list )){
$ Destructor = "_". get_class ($ objref );
If (method_exists ($ objref, $ destructor )){
$ Objref-> $ destructor ();
}
}
// Clear the list of registered objects,
// Prevent repeated calls
$ _ PEAR_destructor_object_list = array ();
}}
....
Register_shutdown_function ("_ PEAR_call_destructors ");
The above code shows how PEAR implements the destructor. in the component functions, it checks whether there are Destructor in the current class, the reference of the current class will be placed in a global list. In _ PEAR_call_destructors, check whether each element in the global list has a corresponding destructor. If yes, then, the global list is cleared.
In the last line of PEAR. php code, call register_shutdown_function ("_ PEAR_call_destructors") and register _ PEAR_call_destructors. in this way, PHP calls back this function when the script is executed. Using destructor, you can do some necessary "aftercare" work before processing user requests and exiting. a typical example is that you can close opened files, disconnect the database and save some data to the disk.
Error handling
PEAR allows you to handle errors in many ways. instead of simply returning an error code or message, you can return a PEAR_Error object, or a new error object derived from PEAR_Error.
The error object in PEAR does not have a specific output format. it can only capture errors, not return too much information to users, or call back a special error processing function. at the same time, even if an error message is output, it forces you to use the HTML format. you can output XML, CSV format, or other custom formats, you only need to derive a new class from PEAR_Error, and then create and "throw" the object of this new class as appropriate.
Simple error handling:
In PEAR, the simplest error handling method is "throw". you only need to create and return a PEAR_Error object. The following is a simple example: function myconnect ($ host = "localhost", $ port = 1080 ){
$ Fp = fsockopen ($ host, $ port, $ errno, $ errstr );
If (! Is_resource ($ fp )){
Return new PEAR_Error ($ errstr, $ errno );
}
Return $ fp;
}
$ Sock = myconnect ();
If (PEAR: isError ($ sock )){
Print "connect error:". $ sock-> getMessage (). "\ n"
}
As shown in the code above, after executing a piece of code that may produce errors, you need to use the PEAR isError to check for errors, you can use the getMessage of PEAR_Error to obtain the last error message. Note: You must use PEAR: isError in key areas.
Use raiseError
After PHP4.0.5, PEAR has two more functions:
SetErrorHandling ($ mode, $ options = null)
RaiseError ($ message = null, $ code = null, $ mode = null, $ options = null, $ userinfo = null)
The former can set the default PEAR error handling mode, and the latter is a packaging function, which returns a PEAR_Error object, which is slightly different from the object directly created and returned PEAR_Error, if $ mode, $ options, and other parameters are omitted, the default value is used to create the PEAR_Error object. you can use setErrorHandling () to customize these default values.
PEAR_Error
PEAR_Error is a base class of the PEAR error object. Unlike PEAR, you can directly create a PEAR_Error instance By: $ error = new PEAR_Error ($ message, $ code, $ mode, $ options, $ userinfo );
$ Message is your error message, $ code is the error number of the error, and the last three parameters are closely related:
$ Mode: the processing mode of this error. the following constants can be used:
PEAR_ERROR_RETURN: returns only the error object (default)
PEAR_ERROR_PRINT: this error message is printed in the build function, but the current program continues to run.
PEAR_ERROR_TRIGGER: trigger an error using PHP's trigger_error (). If you have set the error processing function or set the PHP error processing level to E_USER_ERROR, the current program will be terminated.
PEAR_ERROR_DIE: print the error and exit. The program is terminated.
PEAR_ERROR_CALLBACK: Use a callback function or method to handle the current error and terminate the program.
$ Options: this parameter takes effect only when $ mode is PEAR_ERROR_TRIGGER and PEAR_ERROR_CALLBACK. for PEAR_ERROR_TRIGGER, $ options must be E_USER_NOTICE, E_USER_WARNING, or E_USER_ERROR, the value is the same as that of trigger_error in PHP. If $ mode is PEAR_ERROR_CALLBACK, $ options can be a string with the name of the function to be called back, or an array of 2 elements, which is an object variable, and a string (indicating the method to be called ).
$ Userinfo: stores additional user information. you can put the relevant debugging information here.
PEAR_Error has some common methods. these methods are not described in the PHP document and are listed here:
Int getMode: returns the current error processing mode, an integer.
String getMessage: returns the current complete error message, a string.
Mixed getCallback: returns the current callback information, which may be the name of the callback function or an array (object, method.
Int getCode: return the error code of the integer type.
String getType: the type of the returned error, that is, the current class name, string.
String getUserInfo: returns the additional user information, a string.
String getDebugInfo: the content is the same as above.
String toString: returns the detailed string description of the current object, including the error processing mode, level, error information, error code, and related callback functions.
Summary
Now, the PEAR introduction is complete. To sum up, if you want to create a PEAR extension application, you need:
Require_once "PEAR. php"
Use class your_pear_extend extends PEAR {} to define your new class.
In your class constructor, call the constructor of the parent class PEAR: function your_pear_extend {
$ This-> PEAR ();
...
}
Define your destructor _ your_pear_extend if needed
If necessary, derive your own error handling class from PEAR_Error
Set your error handling mode and trigger the error when appropriate.
After executing code that may produce errors, use PEAR: isError ($ obj) to capture the corresponding errors.
Implement your own functions.
In the core release of PEAR, there are already many excellent application modules, such as PHPDoc, Cache, and HTML.