Pear of the repository of PHP

Source: Internet
Author: User
Tags call back getmessage html form pear php error
This article is to introduce the content of PHP is a treasure trove of pear, here to share to you, the need for friends can refer to


You may already be a veteran of PHP and write a lot of great code. But if you want to add them to your current project now, are you struggling? Your friend wants to use your code as a module in his project, but you find that you're using a different coding style, adapting it, or even rewriting one!
Please come with me, use the pear standard to write your PHP program, your program will have more vitality, your program and code will be very convenient and other master code together, pear like CPAN for Perl, will allow PHP to generate higher energy.

What is Pear
Pear is an abbreviation for the PHP extension and application library (the PHP Extension and application Repository). It is a PHP extension and application of a code warehouse, in short, pear is the PHP cpan.

Why use pear?
PHP is a very good scripting language, concise and efficient, with the release of 4.0, more and more people use it for dynamic website development, it can be said that PHP has become one of the best Internet development language, especially for those who need to be able to quickly, PHP is the preferred language for developers of web sites that develop small-to-medium-sized business applications efficiently. But with the increasing application of PHP, the lack of uniform standards and effective management of these applications, it is difficult for the PHP community to share each other's code and applications as easily as people in the Perl community, Because PHP lacks a unified code base like CPAN to classify and manage the code modules of the application (everyone familiar with Perl knows that Cpan is a huge Perl extension module repository, the application modules can be placed under the appropriate directory under CPAN, others can be easily reused, Of course, you also need to follow the guidelines when you write application modules. )

For this reason, pear came into being and, starting with 4.04, was distributed along with the PHP core.

What benefits can pear bring to me?
1. As mentioned earlier, Pear manages the Pear application code base according to a certain classification, your pear code can be organized into the appropriate directory, others can easily retrieve and share your results.

2.PEAR is not just a code warehouse, it is also a standard, using this standard to write your PHP code, will enhance the readability of your program, reusability, reduce the chance of error.

3.PEAR provides you with 2 classes to build a framework that implements such functions as destructors, error trapping, which you can use with inheritance.

Coding Rules for Pear
Pear's coding rules include indentation rules, control structures, function calls, function definitions, annotations, including code, PHP tags, file header comment blocks, CVS tags, url samples, and constant naming of these 11 aspects. The following is a brief introduction to:

Indentation Rules:
You need to use 4 spaces in pear to indent the code without using 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.

But you like me to use (X) Emacs to edit php files, I highly recommend you to install Php-mode, so when you write pear code, it will automatically adjust your indentation style, of course, php-mode there are many excellent features, You can download the latest version of Php-mode from the resources list.

Control structure:
The control structure described here includes the following: If for and while switch. For control structures, in keywords such as if for. The next one is empty, and then the parentheses are controlled, so that it is not confused with the function call, and you should try to use the curly brace {} as fully as possible, even if it is syntactically optional. This prevents you from having to add new lines of code in the future to produce logical doubts or errors. Here is a sample:
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 spaces between the functions name and the opening parenthesis (there should be no space between the separated comma and the next argument, and no space between the last argument and the closing parenthesis). The following is a standard function call;
$result = foo ($param 1, $param 2, $param 3);
Non-canonical notation:
$result =foo ($param 1, $param 2, $param 3);
$result =foo ($param 1, $param 2, $param 3);




In addition, if you want to assign a value to the returned result of a function, there is a space between the equal sign and the assigned variable, and if it is a series of related assignment statements, you add the appropriate spaces to align them, like this:
$result 1 = $foo ($param 1, $param 2, $param 3);
$var 2 = $foo ($param 3);
$var 3 = $foo ($param 4, $param 5);




function definition:
The function definition follows the custom of "one True brace":

Function Connect (& $DSN, $persistent = False) {if (Is_array ($DSN)) {$dsninfo = &&dsn;} else {$dsninfo = DB: :p Arsedsn ($DSN); } if (! $dsninfo! $dsninfo [' Phptype ']) {return $this->raiseerror ();} return true; }



As shown above, optional parameters are at the end of the parameter table and always try to return meaningful function values.

About Comments:
The online documentation for the class should be able to be converted by Phpdoc, just like Javadoc. Phpdoc is also a pear application, more detailed introduction you can go to http://www.phpdoc.de/view. In addition to the class of online documentation, it is recommended that you use non-document-nature annotations to interpret your code, and when you see a piece of code, think: Oh, I don't think I need to describe it in a document. Then you'd better make a simple comment on the code so that you don't forget how it works. In the form of annotations, c/*/and C + +//are good, however, do not use Perl or the Shell's # notation.

Include Code:
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, which will ensure that the file you want to include is included only once, And these 2 statements share the same file list, so you don't have to worry about the two being confused, and once require_once contains a file, Include_once won't repeat the same file, and vice versa.

PHP Code Tags:
Use <?php?> to define your PHP code at any time, instead of simply using <??, which ensures pear compatibility and facilitates cross-platform porting.

Comment Declaration for file header:
All PHP code files that need to be included in the Pear core, at the beginning of the file, you must add the following comment statement:
/* Vim:set expandtab tabstop=4 shiftwidth=4: */

// +----------------------------------------------------------------------+

// | PHP version 4.0 |

// +----------------------------------------------------------------------+

// | Copyright (c) 1997, 1998, 1999, 2001, the PHP Group |

// +----------------------------------------------------------------------+

// | This source file was subject to version 2.0 of the PHP license, |

// | That's bundled with the "This" file LICENSE, and is |

// | Available at through-World-wide-web at |

// | Http://www.php.net/license/2_02.txt. |

// | If you do not receive a copy of the PHP license and is 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 also have a similar comment block at the beginning of the file that identifies the copyright, the agreement, the author, and so on. It also joins Vim's modeline in the first line, so that it can maintain pear code style in vim.

CVS Tags:
As shown above, include the CVS ID tag in each file, if you edit or modify the file does not have this tag, then please join, or replace the original file similar expressions (such as "last Modified" and so on)

URL Sample:
You can refer to RFC 2606 and use "www.example.com" as a sample of all URLs.

Constant Name:
Constants should be capitalized as much as possible, to make it easier to understand, use underscores to split each word. At the same time, you should prefix the package or class name where the constants are located. For example, constants in a bug class should start with Bug_. The above is the coding rules of pear, detailed coding rules can refer to the description of the Coding_standdard file in pear. To better understand these coding rules, you can also refer to the code of the existing Pear core module.

Getting Started with pear

PEAR
Using pear is simple, 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 coding rules that you said earlier, and then you can implement what you want to do inside your class. Let's start with a discussion, in fact pear provides us with 2 predefined classes:
PEAR: This is the base class for PEAR, and all PEAR extensions are derived from its inheritance.
Pear_error:pear the base class for error handling, you can choose to derive your own error-handling class.

In general, you should not create an instance of pear directly, but instead create a new class yourself, and then recreate the instance of the new class. As a base class, Pear provides us with some useful functions, most notably destructors and error handling.

Destructors
PHP supports constructors, but does not support destructors, but PHP provides the register_shutdown_function () function, which enables callbacks to registered functions before the script terminates, so Pear uses this feature to provide a simulation of the destructor. If you have a pear subclass called Mypear, then in the Mypear class you can define a function, the function name is an underscore and your class name, _mypear (), which is the destructor of this class. However, this destructor is not the same as the destructor in C + +, it does not execute when the object is deleted, but at the end of the script, it is just a simulation. Because Register_shutdown_function () is used, the information printed in your destructor will not be returned to the browser. In addition, in your constructor, you need to call the constructor of its parent class, because PHP does not automatically call the parent class's constructor, and the destructor needs to be registered in the Pear constructor, we can look at the source code of Pear:

<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=%s\n", Get_class ($this));} ... function _pear_call_des Tructors () {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 repeated calls to $_pear_destructor_object_list = Array (); }} ..... register_shutdown_function ("_pear_call_destructors"); </code> 



The above code shows how PEAR implements the destructor, and in the component function, checks whether there is a destructor in the current class, and if so, puts a reference to the current class into a global list, in _pear_call_destructors, Checks whether each element in the global list has a corresponding destructor, if any, calls it, and finally empties the global list.

in the last line of code for pear.php, call Register_shutdown_function ("_pear_call_destructors"), register _pear_call_destructors, and PHP will callback this function when the script is finished. Using destructors, you can do the necessary "aftercare" work before you exit the user's request, typically by closing open files, disconnecting the database, storing some data in disk, and so on.

Error Handling in
Pear allows you to handle errors in a number of ways, instead of simply returning an error code or the wrong information, you can return a Pear_error object, or a new Error object derived from Pear_error. The Error object in the

Pear does not qualify a specific output form, it can simply catch an error, not give the user too much information, or go back to a special error handler, and even if the output error message, it also forces you must be HTML form, you can output XML, CSV form, or other form of your own definition, you just need to derive a new class from Pear_error and then create and "throw" the object of the new class at the appropriate time.

Simple error handling:
in pear, the simplest error handling is to "throw" the error, you simply create and return a Pear_error object. The following is a simple example:

<code> function Myconnect ($host = "localhost", $port = +) {$fp = Fsockopen ($host, $port, $errno, $ERRSTR); 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 code above, after executing a piece of code that might produce an error, you need to use Pear's iserror to detect an error, and you can use Pear_error's getmessage to get the most recent error message. Note: Be sure to use pear::iserror in a critical place

Using 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 default error handling mode, the latter is a wrapper function, return a Pear_error object, and directly create and return Pear_error object slightly different is, if omitted $mode, $options parameters, It uses the default values to create this Pear_error object, which you can customize with seterrorhandling ().

Pear_error
Pear_error is a base class for PEAR Error objects, unlike PEAR, in general, you can create an instance of Pear_error directly, creating the way:
$error = new Pear_error ($message, $code, $mode, $options, $userinfo);

$message is your error message, $code is the error number of the error, and the following 3 parameters are closely related:
$mode: This is the wrong processing mode and can be the following constants:
Pear_error_return: Returns the Error object only (default)
Pear_error_print: This error message is printed in the build function, but the current program continues to run.
Pear_error_trigger: Use PHP trigger_error () to trigger an error, if you have set the error handling function, or if you set PHP error handling level to E_user_error, then the current program will be terminated.
Pear_error_die: Print error and exit, program terminated.
Pear_error_callback: A callback function or method is used to handle the current error and the program terminates.
$options: This parameter only works when $mode is Pear_error_trigger and pear_error_callback, and if it is Pear_error_trigger, $options must be e_user_ NOTICE, e_user_warning, or E_user_error, one of the 3 constants, is consistent with the value of Trigger_error in PHP. If $mode is Pear_error_callback, the $options can be a string, the function name to call back, or an array of 2 elements, one object variable, and one string (indicating the method to invoke).
$userinfo: To store additional user information, you can put the relevant debugging information here.

There are some commonly used methods in Pear_error, these methods are not described in PHP text block, here are listed:

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, possibly the callback function name, or an array of (objects, methods).
int GetCode: Returns the error code for the integer type.
String GetType: Returns the type of the error, which is the current class name, String.
String GetUserInfo: Returns the appended user information, string.
String Getdebuginfo: Same as the content.
String toString: Returns a detailed string description of the current object, including error-handling patterns, levels, error messages, error codes, related callback functions, and so on.

Summarize
At this point, the introduction of pear is over. In a nutshell, if you want to do 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 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
Set your error handling mode and trigger an error when appropriate.
After executing the code that could produce the error, use Pear::iserror ($obj) to catch the corresponding error.
Implement your own functionality.
In the latest PHP4.05 Pear core release, there are a number of excellent application modules, such as: phpdoc,cache,html ... Of course, compared to cpan, pear is just starting to need the PHP community to work together to improve it, enhance it, PHP will become more and more powerful.


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.