Introduction to pear: Use pear to write your next php program
Content:
What is a pear
Why use pear?
What benefits can pear bring to me?
Pear encoding rules start using pear
Summary of relevant resources and author introduction
Pan Fan (night sailer) ( [email protected] )
Beijing Saidi.com Information Technology Co., Ltd.
In June 2001 you were probably already a PHP veteran and had written a lot of great code. But if you want to add them to your current project now, is it a bit difficult? Your friend wants to use your code as a module in his project, but you find that you use completely different coding styles. Let him adapt, or even rewrite it!
Please follow me and write your PHP program using the pear standard. Your program will have greater vitality. Your program and code will be easily integrated with other experts' codes. Pear is like cpan for Like perl, it will make php generate higher power.
What is a pair
Pear is the abbreviation of the php extension and application repository. It is a code repository for PHP extensions and applications. Simply put, pear is PHP's cpan.
Why use pear?
PHP is a very excellent scripting language, concise and efficient. With the release of 4.0, more and more people are using it to develop dynamic websites. It can be said that PHP has become one of the best Internet development languages, especially For those website developers who need to be able to develop small and medium-sized business applications quickly and efficiently, PHP is the language of choice. However, with the increasing number of PHP applications, there is a lack of unified standards and effective management for these applications. Therefore, it is difficult for the PHP community to share each other's codes and applications as conveniently as people in the Perl community, because PHP lacks the ability to share code and applications like Cpan. A unified code base to classify and manage application code modules (anyone familiar with Perl knows that cpan is a huge Perl extension module warehouse. The written application modules can be placed in the appropriate classification directory under cpan, and other people can Very easy to reuse, of course, you also need to follow the guidelines when writing application modules).
For this reason, pear came into being, and starting from 4.04, it was distributed with the PHP core.
What benefits can pear bring to me?
1. As mentioned above, pear manages the pear application code base according to certain categories. Your pear code can be organized into appropriate directories, and other people can easily retrieve and share your results.
2. Pear is not only a code repository, it is 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.
3. Pear builds a framework for you by providing 2 classes to implement functions such as destructors and error catching. You can use these functions through inheritance.
Coding rules for pear
Pear's coding rules include indentation rules, control structures, function calls, function definitions, comments, containing code, PHP tags, comment blocks in file headers, cvs tags, URL samples, and naming of constants. Here is a brief introduction:
Indentation rules:
You need to use 4 spaces in pear to indent the code, and do not use tabs. 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.
But if you like to use (x)emacs to edit php files like me, I strongly recommend you to install php-mode, so that when you write pear code, it will automatically adjust your indentation style. Of course, php-mode has many more Very nice feature, you can download the latest version of php-mode from the resource list.
Control structure:
The control structures mentioned here include: if for while switch, etc. For control structures, there should be a space after the keyword (such as if for ..), and then the control parentheses, so that it will not be confused with function calls. In addition, you should try to use curly braces {} as completely as possible. Even if it is syntactically optional. This will prevent logical confusion or errors when you need to add new lines of code in the future. 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 calls, there should be no space between the function name and the opening bracket ( (), for function parameters, there should be the same space separation between the delimiting comma and the next parameter, and there should be no space between the last parameter and the closing bracket. Below is a standard function call;
$result = foo($param1, $param2, $param3);
Irregular writing:
$result=foo ($param1,$param2,$param3);
$result=foo( $param1,$param2, $param3 );
In addition, if you want to assign the return result of the function, there must be a space between the equal sign and the assigned variable. At the same time, if it is a series of related assignment statements, you add appropriate spaces to align them, like this :
$result1 = $foo($param1, $param2, $param3);
$var2 = $foo($param3);
$var3 = $foo($param4, $param5);
Function definition:
Function definitions follow 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 should be at the end of the parameter list, and always try to return meaningful function values.
Regarding comments:
For online documentation of classes, it should be able to be converted by phpdoc, just like javadoc. phpdoc is also a pear application. For a more detailed introduction, you can go to http://www.phpdoc.de/ to view it. In addition to online documentation of classes, it is recommended that you use non-documentation comments to explain your code. When you see a piece of code, you think: Oh, I don't think you need to describe it carefully in the documentation. Then you'd better give this code a simple comment to prevent you from forgetting how it works. For the form of comments, c's /* */ and c++'s // are both good. However, do not use perl or shell's # comment method.
Contains code:
Whenever you need to unconditionally include a class file, you must use require_once; when you need to conditionally include a class file, you must use include_once; this ensures that the file you want to include will only be included once, and these 2 Both statements share the same file list, so you don't have to worry about the two getting confused. Once require_once includes a file, include_once will not include the same file again, and vice versa.
php code markup:
Always use <?php ?> to define your PHP code instead of simply using <? ?>. This ensures pear compatibility and facilitates cross-platform porting.
Comment declaration in the file header:
For all PHP code files that need to be included in the pear core release, you must add the following comment statement at the beginning of the file:
/* 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 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 |
// |[email protected] 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 also have such a similar comment block at the beginning of the file, indicating copyright, agreement, author, etc. At the same time, vim's modeline is also added to the first line, so that pear's code style can be maintained in vim.
cvs tag:
As shown above, add the CVS ID tag to each file. If the file you edit or modify does not have this tag, please add it, or replace it with a similar expression in the original file (such as "last modified" etc)
url sample:
You can refer to RFC 2606 and use " http://www.example.com " as all URL samples.
Constant naming:
Constants should be written in uppercase when possible, and to make it easier to understand, use underscores to separate each word. At the same time, you should prefix the package name or class name where the constant is located. For example, the constants in the bug class should start with bug_. The above are the coding rules of pear. For detailed coding rules, please refer to the description of the coding_standard file in 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
Using pear is easy, you just need to define your own pear program like this:
require_once "pear.php";
class your_class_name extends pear{
Your class definition...
}
Of course, you need to abide by the pear coding rules mentioned earlier, and then you can implement what you want to do inside your class. Next, let's discuss it. In fact, pear provides us with 2 predefined classes:
pear: This is the base class of pear, and all pear extensions must inherit and derive from it.
pear_error: The base class of pear's error handling. You can choose to derive your own error handling class.
Generally speaking, you should not create an instance of pear directly, but derive a new class yourself and then create an instance of this new class. As a base class, pear provides us with some useful functions, the most important ones are destructors and error handling destructors.
PHP supports constructors, but does not support destructors. However, PHP provides the register_shutdown_function() function, which can call back the registered function before the script terminates. Therefore, pear uses this feature to provide simulation of the destructor. If you have a subclass of pear, called mypear, then in the mypear class, you can define a function. The function name is an underscore plus your class name, _mypear(). This function is the destructor of this class. However, this destructor is different from the destructor in C++. It will not be executed when the object is deleted, but when the script ends. After all, this is just a simulation. Since register_shutdown_function() is used, the printed information will not be returned to the browser in your destructor. In addition, in your constructor, you need to call the constructor of its parent class, because PHP will not automatically call the constructor of the parent class, and the destructor needs to be registered in the constructor of pear. We can look at pear Source code:
<code>
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=%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();
}
}
//Clear the registered object list,
//Prevent repeated calls
$_pear_destructor_object_list = array();
}
}
....
register_shutdown_function("_pear_call_destructors");
</code>
The above code shows how pear implements the destructor. In the component function, it will check whether there is a destructor in the current class. If so, then the reference of the current class will be put into a global list, in _ In pear_call_destructors, check whether each element in the global list has a corresponding destructor, if so, call it, and finally clear the global list.
In the last line of code in pear.php, call register_shutdown_function("_pear_call_destructors") to register _pear_call_destructors. In this way, when the script is executed, PHP will call back this function. Using the destructor, you can do some necessary "aftercare" work before exiting after processing the user's request. Typical examples are that you can close open files, disconnect from the database, and store certain data on the disk. etc.
Error handling
Pear allows you to handle errors in many ways. You not only simply return an error code or error information, but you can return a pear_error object, or a new error object derived from pear_error.
The error object in pear does not limit the specific output form. It can just capture the error without returning too much information to the user, or it can call back a special error handling function. At the same time, even if it outputs error information, it can also You are forced to use html format. You can output xml, csv format, or other formats defined by yourself. You only need to derive a new class from pear_error, and then create and "throw" this new class at the appropriate time. object on it.
Simple error handling:
In pear, the simplest error handling is to "throw" the error. You simply create and return a pear_error object. Here's a simple example:
<code>
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()."<br>n"
}
</code>
As shown in the above code, after executing a piece of code that may produce 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 obtain the latest error message. Note: Be sure to use pear::iserror in key places
Use raiseerror
After php4.0.5, pear has 2 more functions:
seterrorhandling($mode, $options = null)
raiseerror($message = null, $code = null, $mode = null,$options = null, $userinfo = null)
The former can set pear's default error handling mode, and the latter is a wrapper function that returns a pear_error object , which is slightly different from directly creating and returning a pear_error object. If you omit parameters such as $mode and $options, it will use default values to create the pear_error object. You can use seterrorhandling() to customize these default values. .
pear_error
pear_error is a base class of pear's error object. Unlike pear, generally speaking, you can directly create an instance of pear_error 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: is the error handling mode, which can be the following constants:
pear_error_return: only returns the error object (default mode)
pear_error_print: Print this error message in the build function, but the current program will continue to run.
pear_error_trigger: Use PHP's trigger_error() to trigger an error. If you have set up an error handling function, or you set PHP's error handling level to e_user_error, the current program will be terminated.
pear_error_die: Print the error and exit, 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 one of the three constants e_user_notice, e_user_warning or e_user_error, which is consistent with the value of trigger_error in PHP. If $mode is pear_error_callback, $options can be a string containing the name of the function to be called back, or an array of 2 elements, respectively an object variable and a string (indicating the method to be called).
$userinfo: Stores additional user information. You can put relevant debugging information here.
There are some commonly used methods in pear_error. These methods are not described in the PHP documentation. They are listed here:
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, which may be the name of the function being called back, or an array of (objects, methods).
int getcode: Returns an integer error code.
string gettype: Returns the wrong type, which is the current class name, string.
string getuserinfo: Returns additional user information, string.
string getdebuginfo: The content is the same as above.
string tostring: Returns a detailed string description of the current object, including error handling mode, level, error information, error code, related callback functions, etc.
In summary, the introduction to pear is over. In summary, if you want to make an extension application of pear, you need to do this:
require_once "pear.php"
Use class your_pear_extend extends pear{} to define your new class.
In the constructor of your class, call the constructor of the parent class pear:
function your_pear_extend{
$this->pear();
...
}
If necessary, define your destructor _your_pear_extend
If necessary, derive your own error handling class from pear_error to set your error handling mode and trigger errors when appropriate.
After executing code that may generate errors, use pear::iserror($obj) to capture the corresponding errors.
Implement your own functionality.
In the latest pear core release of php4.05, there are already many excellent application modules, such as: phpdoc, cache, html... Of course, compared to cpan, pear is just getting started and needs people from the php community. With our joint efforts to improve it and enhance it, php will become more and more powerful.
Related resources
pearHomepage
php homepage
phpdoc home page, which can generate API documents similar to javadoc from your pear application source code
php-mode for xemacs/emacs, provides PHP syntax support for emacs/xemacs, and can well support pear code style
vim home page, a very good editor, also has good support for php