You may already be a veteran of PHP and write a lot of great code. But is it a bit of a struggle if you want to add them to your current project now? Your friend wants to use your code as a module in his project, but you find that you are using a different coding style to adapt to it, or even rewrite it!
Come with me, please. Using the pear Standard to write your PHP program, your program will have more energy, your program and code will be easily integrated with other master code, pear, like CPAN for Perl, will make PHP more energy.
What is Pear
Pear is an abbreviation of the PHP extension and the application library (the PHP Extension and application Repository). It is a PHP extension and application of a code warehouse, simply, pear is the PHP cpan.
Why do you use pear?
PHP is a very good scripting language, concise, efficient, with the release of 4.0, more and more people use it for dynamic web site 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 Web developers who efficiently develop small and medium sized business applications. But with the growing application of PHP and 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 the code modules that govern applications (people familiar with Perl know that Cpan is a huge Perl expansion module warehouse, the written application module can be placed under the appropriate classification directory below CPAN, the other people can easily reuse, Of course, you also need to follow the guidelines when writing application modules. )
For this reason, pear came into being and, starting with 4.04, was distributed along with the PHP core.
What good can pear bring me?
1. As mentioned above, pear manages the Pear application code base according to certain classifications, and your pear code can be organized into the appropriate directory where other people can easily retrieve and share your results.
2.PEAR is not just a code warehouse, it is also a standard, use this standard to write your PHP code, will enhance your program readability, reusability, reduce the chance of error.
3.PEAR builds a framework for you by providing 2 classes, implementing such functions as destructors and error trapping, which you can use to inherit.
Pear's Coding rules
Pear's coding rules include indentation rules, control structures, function calls, function definitions, annotations, include code, PHP tags, file header annotation blocks, CVS tags, url samples, and constant naming of these 11 aspects. Here is a brief introduction to:
Indent rules:
Pear requires 4 spaces to indent the code without using the TAB key. If you use Vim, put the following settings into your ~/.VIMRC:
Set Expandtab
Set shiftwidth=4
Set tabstop=4
If you use Emacs/xemacs, you need to set the Indent-tabs-mode to nil.
But you like me to edit php files with (X) Emacs, and I highly recommend that you install Php-mode so that when you write pear code, it automatically adjusts your indentation style, and of course Php-mode has many excellent features, You can download the latest version of Php-mode from the list of resources.
Control structure:
The control structure described here includes: if for the while switch, and so on. For control structures, in keywords such as if for ... Then you have to empty a grid and then follow the control parentheses, so that it's not confusing with the function call, and you should try to use the curly braces {} as completely as possible, even if it's syntactically optional. This prevents you from having to add new lines of code later to create a logical confusion or error. 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 name of the functions and the opening parenthesis (there should be no space between the separated comma and the next argument for function arguments), and there should be no spaces 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 wording:
$result =foo ($param 1, $param 2, $param 3);
$result =foo ($param 1, $param 2, $param 3);
In addition, if you want to assign the return result of a function to a value, there is a space between the equals sign and the variable being assigned, and if you have 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 "one True brace" custom:
Function Connect (& $DSN, $persistent = False)
{
if (Is_array ($DSN)) {
$dsninfo = &&dsn;
} else {
$dsninfo = DB::p arsedsn ($DSN);
}
As shown above, the optional parameters are at the end of the parameter table and always try to return meaningful function values.
About notes:
The online documentation for the class should be able to be Phpdoc converted, just like Javadoc does. Phpdoc is also a pear application, more detailed introduction you can go to http://www.phpdoc.de/view. In addition to the online documentation for the class, it is recommended that you interpret your code using a document-less annotation, and when you see a piece of code, think: Oh, I don't think I need to describe it in the document. Then you'd better make a simple comment on the code to prevent you from forgetting how they work. For the form of annotations, C's/*/C + + is good, but do not use Perl or the Shell's # annotation method.
Include Code:
Whenever you need to include a class file unconditionally, you must use requre_once; When you need a condition to include a class file, you must use include_once to 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 confusing them, and once require_once contains a file, Include_once does not repeat the same file, and vice versa.
PHP Code Tags:
Use <?php?> to define your PHP code at all times, rather than simply using the???, so that you can ensure pear compatibility, but also facilitate cross-platform porting.
Note Declaration for file headers:
All the PHP code files that need to be included in the Pear core release, at the beginning of the file, you must add the following comment statement:
/* Vim:set expandtab tabstop=4 shiftwidth=4: * *
For files that are not in the Pear core code base, it is recommended that you also have a similar annotation block at the beginning of the file, indicating copyrights, agreements, authors, and so on. Also add Vim's modeline to the first line so that you can keep Pear's code style in vim.
CVS Tag:
As shown above, add CVS ID tags to each file and if you do not have the tag in the edited or modified file, join, or replace a similar representation in the original file (such as "last Modified", etc.)
URL Sample:
You can refer to RFC 2606 and use "www.example.com" as a sample of all URLs.
Constant Name:
Constants should use uppercase as much as possible, and for ease of understanding, use underscores to separate each word. At the same time, you should prefix the package name where the constant is or the class masterpiece. For example, constants in the bug class should start with Bug_. These are the code rules for pear, and 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 for the existing Pear core module.
Start using Pear
PEAR
Using pear is simple, you just have 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 mentioned above, and then you can implement what you want to do within your class. Now, let's start with a discussion, and in fact, Pear provides us with 2 predefined classes:
Pear: This is the base class for pear, and all of the 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 classes.
In general, you should not create an instance of pear directly, but instead derive a new class by yourself, and then create an instance of the new class. As a base class, Pear provides us with some useful features, the most important being destructors and error handling
destructor
PHP supports constructors, but does not support destructors, but PHP provides the register_shutdown_function () function to callback the registered function before the script terminates, so Pear uses this feature to provide a 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 underlined plus 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 does not execute when the object is deleted, but at the end of the script, after all, it is just a simulation. Because the Register_shutdown_function () is used, the printed information will not be returned to the browser in your destructor. Also, in your constructor, you need to call the constructor of its parent class, because PHP does not automatically invoke the parent class constructor, and destructors need to be registered in Pear's constructor, we can look at the source 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_destructors () {
Global $_pear_destructor_object_list;
if (Is_array ($_pear_destructor_object_list) && sizeof ($_pear_destructor_object_list)) {
Reset ($_pear_destructor_object_list);
while (the 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,
The above code shows how PEAR implements destructors, in component functions, checks whether there are destructors in the current class, and if so, puts the reference of the current class into a global list, in _pear_call_destructors, Checks whether each element in the global list has a corresponding destructor, if so, call it, and then empty the global list.
At the last line of code in pear.php, call Register_shutdown_function ("_pear_call_destructors"), register _pear_call_destructors, so that When the script completes, PHP will call back the function. With destructors, you can do the necessary "cleanup" work before you finish processing the user's request, typically by closing the open file, disconnecting the database, storing some data in the disk, and so on.
Error handling
Pear allows you to handle errors in many ways, not just by simply returning an error code, or by the wrong message, but by returning a Pear_error object or a new Error object derived from Pear_error.
The wrong object in pear does not have a specific output form. It can simply catch errors, not return too much information to the user, or go back to a special error handler, and even if you output an error message, it forces you to be an HTML form, you can output xml,csv form, or other forms you define, you just need to derive a new class from Pear_error, and then create and "throw" the object of the new class at the right time.
Simple error Handling:
In pear, the simplest error handling is "Throw" the error, you simply create and return to a Pear_error object. The following is 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;
}
As shown in the code above, you need to use Pear's iserror to detect any errors after executing a code that may produce 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 key places
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 the pear default error handling mode, which is a wrapper function that returns a Pear_error object, and a slightly different object that directly creates and returns PEAR_ERROR, if omitted $mode, $options and other parameters, It uses the default value to create this Pear_error object, which you can customize using seterrorhandling ().
Pear_error
Pear_error is a base class for pear's wrong object, unlike pear, in general, you can create an instance of Pear_error directly, creating a 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 latter 3 parameters are closely related:
$mode: This is the wrong mode of handling and can be the following constants:
Pear_error_return: Just return 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: Use PHP's Trigger_error () to trigger an error, if you have set the error handling function, or you set the error handling level of PHP to E_user_error, then the current program will be terminated.
Pear_error_die: Print error and exit, program terminated.
Pear_error_callback: Using a callback function or method to handle the current error, 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 these 3 constants, is consistent with the Trigger_error values in PHP. If $mode is Pear_error_callback, $options can be a string, the function name to be called back, or an array of 2 elements, an object variable, and a string (indicating the method to be invoked).
$userinfo: Store Additional user information, you can put the relevant debugging information here.
There are some commonly used methods in Pear_error, which are not described in the PHP text, and 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, either as a callback function name or as an array of (object, method).
int GetCode: Returns an integer error code.
String GetType: Returns the type of the error, which is the current class name, String.
String GetUserInfo: Returns additional user information, string.
String Getdebuginfo: Content Ibid.
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
So far, the introduction of pear is over. In a nutshell, if you want to do an extended 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 needed, derive your own error-handling class from Pear_error
Set your error handling mode and trigger the error when appropriate.
After executing the code that may produce an error, catch the corresponding error with Pear::iserror ($obj).
Realize your own function.
In the latest PHP4.05 Pear core release, there are already a number of excellent application modules, such as: phpdoc,cache,html ... Of course, as opposed to cpan, pear is just getting started, needs the people of the PHP community to work together to improve it, enhance it, PHP will become more and more powerful.
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.