What is PearPear is an abbreviation for PHP extension and application library. It is a PHP extension and application of a code warehouse, simply, PEAR is PHP's CPAN.
Why use PEAR? PHP is a very excellent scripting language, simple, efficient, with 4.0 release, more and more people use it to develop dynamic websites, can say that PHP has become one of the best Internet development languages, especially For those website developers who need to be able to quickly and efficiently develop small-scale commercial applications, PHP is the preferred language. However, with the increasing application of PHP, there is a lack of unified standards and effective management for these applications, so the PHP community is very difficult to share each other's code and application, because PHP lacks like CPAN. Unified code library to classify the code module for administrative applications (those who are familiar with Perl know that CPAN is a huge perl extension module warehouse, the application module written in the appropriate classification directory below the CPAN, others can It is very convenient to reuse, of course, you need to comply with the guidelines when you write the application module.)
To this end, PEAR will be born, and from 4.04, PHP is distributed together with the PHP core.
What benefits will PEAR bring me? 1. As mentioned earlier, Pear manages the PEAR application code library according to certain classification, and your PEAR code can be organized into the appropriate directory, other people can easily retrieve and share your results.
2. Ppear is more than just a code warehouse, it is also a standard, using this standard to write your PHP code, will enhance your program readability, reuse, and reduce the chances of error.
3. PEAR has built a framework for you to set up a framework for you, such as an analyte function, error capture, you can use these features through inheritance.
PEAR's encoding rules PEAR encoding rules include indent rules, control structures, function calls, function definitions, comments, including code, PHP tags, file headers, CVS tags, URL samples, and naming of constants. The following is a brief introduction:
Indenge rules: 4 spaces are required to shrink code in PEAR and do not use Tab. If you use Vim, put the following settings in your ~ / .vimrc:
SET ExpandTab
Set ShiftWidth = 4
SET TABSTOP = 4
If you use Emacs / Xemacs, you need to set Indent-Tabs-Mode to NIL. However, you like I like to edit the PHP file with (x) Emacs, I strongly recommend that you install PHP-MODE, so when you write PEAR code, it will automatically adjust your shrinking style, of course, PHP-Mode has many Very excellent features, you can download the latest version of PHP-MODE from places in the resource list. Control structure: The control structure described here includes: if for while switch, etc. For control structures, you have to empty a grid after keywords (such as if for ..), then follow the control parentheses, so that you will not be confused with the function call. In addition, you should try to use the curly brackets {} as possible. Even from grammar is optional. This prevents logically doubts or errors when you need to add new code lines. Here is a sample: IF ((Condition 1) && (Condition 2)) {
Statement 1;
ESLEF (condition 3) || (condition 4)) {
Statement 2;
} else {
Statement 3;
}
Function call: For function calls, function names, and left parenthesis (no space between the function, the function parameters, between the separated comma and the next parameter must have the same space separation, the last parameter and the right brackets cannot be Space. Below is a standard function call;
$ Result = Foo ($ Param1, $ Param2, $ Param3);
Unregulated Writings:
$ Result = Foo ($ Param1, $ Param2, $ Param3);
$ Result = Foo ($ Param1, $ Param2, $ Param3);
In addition, if you want to assign a function's return result, there is a space between the equivalent and the value of the value, and if it is a series of related assignment statements, you add the appropriate space to make them align, like this :
$ Result1 = $ FOO ($ Param1, $ Param2, $ Param3);
$ VAR2 = $ foo ($ param3);
$ VAR3 = $ FOO ($ Param4, $ Param5;
Function Definition: Function Definition Follow "One True Brace" custom:
Function Connect (& $ DSN, $ PERSIStent = false)
{
IF (IS_ARRAY ($ DSN)) {
$ dsninfo = && dsn;
} else {
$ dsninfo = db :: pasedsn ($ dsn);
}
IF (! $ dsninfo ||! $ dsninfo ['phpoType']) {
Return $ this-> raiseerror ();
}
Return True;
}
As shown above, optional parameters are in the end of the parameter table, and always try to return a meaningful function value. About Note: For the online document of the class, it should be able to convert by phpdoc, just like JavaDoc. PHPDOC is also a PEAR app, more detailed introduction you can go to http://www.phpdoc.de/ view. In addition to the online documentation of the class, it is recommended that you should use non-document nature annotations to interpret your code, when you see a code: Oh, I don't need to describe it carefully in the document. Then you make a simple comment for this code, this prevents you from working on how they work. For the form of the comment, C's / * / and C // are good, but do not use Perl or Shell # annotation mode. Include code: Whenever you need unconditionally containing a Class file, you have to use remove_once; when you need the condition to include entertaire file, you must use include_once; this can guarantee that the file you want is once, And these two statements share the same file list, so you don't have to worry that both will be confused. Once Require_Once contains a file, INCLUDE_ONCE does not repeat the same file, vice versa. PHP code tag: Use Php?> To define your PHP code at any time, not to simply use >, Which ensures the compatibility of PEAR, which is also beneficial to cross-platform transplantation. File head annotation declaration: All PHP code files that need to be included in the Pear core. When the file starts, you must join the following annotation declaration: / * vim: set expandtab tabstop = 4 ShiftWidth = 4: * /
// --------------------------------------------- -----------------------
// | PHP Version 4.0 |
// --------------------------------------------- -----------------------
// | CopyRight (C) 1997, 1998, 1999, 2000, 2001 The PHP Group |
// --------------------------------------------- -----------------------
// | this Source File Is Subject to Version 2.0 of the PHP license, |
// | That Bundled with this package in the file license, and @ @ t |
/ / | 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 that are not in the Pear core code base, it is recommended that you have such a similar comment block in the beginning of the file, indicate copyright, protocol, author, etc. At the same time, the Modeline of Vim is also added in the first line, so that the PEAR's code style can be kept in the VIM. CVS tag: As shown above, add CVS ID tags in each file, if you have no marks in your editing or modified file, please join, or replace the original form of performance (eg, " Last Modified ", etc.) URL sample: You can refer to RFC 2606, using" www.example.com "as all URL samples. Constant naming: Constant should try to use uppercase, in order to facilitate understanding, use underscores to segment each word. At the same time, you should have the package names in constants or class names as a prefix. For example, constants in the bug class should start with BUG_. The above is the coding rule of PEAR, and the detailed encoding rules can refer to the instructions for the Coding_standDard file in the PEAR. In order to better understand these coding rules, you can also refer to the code of the existing Pear core module.
Start using PEAR
Pear uses PEAR very simple, you only 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 previous PEAR coding rules, then you can achieve what you have to do in your class. Below, we will discuss it, in fact, PEAR provides us with 2 predefined classes: PEAR: This is the base class of PEAR, all PEAR extensions must be derived from it. Pear_ERROR: PEAR's error handling base class, you can choose to send a class that is born out of your own error handling. In general, you should not create an instance of PEAR directly, but you have to derive a new class yourself, then create an instance of this new class. As the base class, Pear provides us with some useful features, the most important thing is the destructor and error handling
The destructor PHP supports constructor, but does not support destructuring functions, but PHP provides a function of register_shutdown_function (), so that PEAR can use this feature to provide the simulation of the destructor using this feature. . If you have a subclass of PEAR, called Mypear, then in the Mypear class, you can define a function, the function name is the underscore, _mypear (), this function is the destructor of this class. However, this destructor and the destructor in C are less than the same, it will not perform when the object is deleted, but at the end of the script, this is just a simulation. Since it is used to use register_shutdown_function (), the print information will not return to the browser in your destructor. In addition, in your constructor, you need to call the constructor of its parent class, because PHP does not automatically call the parent class constructor, and the destructor needs to register in the PEAR constructor, we can take a look at PEAR Source code:
Function pear () {
IF ($ this, "_". get_class ($ this))) {
Global $ _PEAR_DESTRUctor_Object_List;
$ _PEAR_DESTRUctor_Object_list [] = && this
}
IF ($ THIS -> _ Debug) {
Printf ("Pear Constructor Called, Class =% SN",
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 ();
}
}
/ / Empty the list of registered objects,
/ / Prevent repetitive calls
$ _PEAR_DESTRUCTOR_Object_list = array ();
}
}
....
Register_shutdown_function ("_ pear_call_destructors);
code>
The above code shows how PEAR implements the destructuring function. In the component function, it will check if there is a destructor in the current class. If there is, then put the current class in a global list, in _ In Pear_Call_Destructors, check if each element in this global list exists, if there is, call it, and finalize the global list. At the last line of Pear.php, call register_shutdown_function ("_ pear_call_destructors"), register _pear_call_destructors, so that when the script is executed, PHP will call this function. Using the destructor, you can do some "good" work before processing the user, to exit the necessary "good" work, typical example is, you can close the open file, disconnect the database, save some data into disk and many more. Error Handling PEAR can make you have a lot of ways to handle errors, you just simply return an error code, or the wrong information, but you can return a pear_error object, or a new error object derived from Pear_ERROR. . The error object in the PEAR does not limit the specific output form, which can be simply captured, do not return too much information to the user, or to call up a special error handler, at the same time, even if the error message is output, it also Forced you must be in the form of html, you can output XML, CSV form, or other forms of your own definition, you only need to derive a new class from Pear_Error, then create and "throw" this new class when appropriate Objects can be. Simple error handling: In PEAR, the simplest error handling is "throw" this error, you can simply create and return a pear_error object. Here 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"
}
code>
As shown above, after executing a piece of code that may generate an error, you need to use PEAR's ISERROR to detect whether there is an error and you can use pear_error's getMessage to get the most recent error message. Note: Be sure to use the use of Pear :: ISERROR in a key place to use RaiseError
After PHP4.0.5, Pear more than 2 functions:
SETERRORHANDLING ($ Mode, $ Options = NULL)
Raiseerror ($ message = null, $ code = null, $ mode = null, $ options = null, $ userinfo = null)
The former can set PEAR default error handling mode, the latter is a package function, returns a pear_error object, and the object created and returned to pear_error is slightly different. If you omit, $ Mode, $ OPTIONS, etc., it will Use the default to create objects of this pear_error, which you can use to customize it using setErrorHandling (). Pear_error pear_error is a base class for PEAR's error objects, and Pear_Ear, in general, you can create Pear_Error instances, create: $ error = new pear_ERROR ($ Message, $ Code, $ Mode, $ Options, $ Userinfo; $ message is your error message, $ code is the error number, the last three parameters are close contact: $ mode: is this error handling mode, you can follow the constant: pear_error_return: only returns the error object (By default) Pear_ERROR_PRINT: Print this error message in the build function, but the current program will continue to run. Pear_ERROR_TRIGGER: Trigger an error using PHP, if you have set an error handler, or you set the PHP's error handling level to e_user_error, then the current program will be terminated. Pear_error_die: Print an error and exits, the program terminates. Pear_error_callback: Use a callback function or method to handle the current error, and the program terminates. $ OPTIONS: This parameter only works when $ mode is pear_error_trigger and pear_error_callback, if it is pear_error_trigger, $ OPTIONS must be an E_USER_NOTICE, E_USER_WARNING or E_USER_ERROR these three regular pieces, which is consistent with the value of Trigger_ERROR in PHP. If $ mode is pear_error_callback, $ Options can be a string, the content is a function name to be called, or an array of 2 elements, which is an object variable, and a string (indicate the method to be called). $ UserInfo: Store additional user information, you can put the relevant debug information here. There are some common methods in Pear_Error, which are not described in the PHP text block.
INT getMode: Returns the current error handling mode, integer. String GetMessage: Returns the current complete error message, string. Mixed getCallback: Returns the current callback information, may be the array of function names, or (objects, methods)). INT getCode: Returns an integer error code. String gettype: Returns the type of error, that is, the current class name, string. String getUserInfo: Returns the additional user information, string. String getDebuginfo: The content is the same. String toString: Returns the detailed string description of the current object, including the error handling mode, level, error message, error code, related callback function, etc. Summary here, the introduction to PEAR is over. In summary, if you want to be a PEAR extension application, you need to do this:
Require_once "pear.php" Use class your_pear_extend extends pear {} to define your new class. In your class constructor, call the parent class PEAR constructor:
Function your_pear_extend {
$ this-> pear ();
...
}
If necessary, define your destructor _Your_pear_extend If needed, send your own error handling classes from pear_error to set your error handling mode and trigger errors when appropriate. After performing the code that may generate an error, use Pear :: ISERROR ($ OBJ) to capture the corresponding error. Realize your own function. In the latest PHP4.05 Pear core release, there have been many excellent application modules, such as phpdoc, cache, html ... of course, PEAR just start, people in PHP communities Common efforts to improve it, enhance it, PHP will get more powerful.
Related Resources PEAR Homepage
PHP homepage
PHPDOC homepage, you can generate API documents similar to Javadoc from your PEAR application source code
PHP-MODE for Xemacs / Emacs, providing PHP's grammatical support for Emacs / Xemacs, which is very good to support PEAR code style
Vim home page, very good editor, support for PHP is also very good
Author briefation Panfan: Beijing Said Data Co., Ltd. Engineer. Mainly engaged in the analysis and conversion of data, as well as related development work. Good at VB, Perl, PHP development and Linux's Chinese culture work. Recent interest is Perl, PHP and XML application, PHP's MVC development model, and Perl-gtk. You can contact him with E-mail: Nightsailer@hotmail.com.