Home > Backend Development > PHP Tutorial > PHP treasure house directory--PEAR_PHP tutorial

PHP treasure house directory--PEAR_PHP tutorial

WBOY
Release: 2016-07-21 16:11:21
Original
742 people have browsed it


You may already be a PHP veteran and have 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 the codes of other experts. PEAR will Like CPAN for PERL, it will cause PHP to generate higher energy.

What is PEARR
PEAR is the abbreviation of 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. First, PHP is the preferred language, especially for those website developers who need to be able to develop small and medium-sized commercial applications quickly and efficiently. However, as the number of PHP applications continues to increase, 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 code and applications as conveniently as people in the PERL community, because PHP lacks the same standards as 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 under the appropriate classification directory under CPAN, and other people can It is easy to reuse. Of course, you also need to follow the guidelines when writing application modules. )

For this reason, PEAR came into being and has been distributed with the PHP core starting from 4.04.

What benefits can PEAR bring to me?
1. As mentioned above, PEAR manages the PEAR application code library 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 just 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 errors. probability.

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.

PEAR coding rules
PEAR coding rules include indentation rules, control structures, function calls, function definitions, comments, included code, PHP tags, file header comment blocks, CVS tags, URL samples For example, these 11 aspects of constant naming. Here is a brief introduction:

Indentation rules:
PEAR requires 4 spaces to indent the code, and no TAB is used. 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 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 also has many excellent features. 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 call, the function name and the left bracket ( There should be no spaces between them. For function parameters, there should be the same space separation between the delimiting comma and the next parameter. There should be no space between the last parameter and the closing parenthesis.The following 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, then in There must be spaces between the variables to be assigned, and 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 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 in the parameter list end, 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 comment forms, C's /* */ and C++'s // are both good. However, do not use Perl or shell's # comment method.

Include code:
Whenever you need to unconditionally include it into a class file, you must use require_once; when you need to conditionally include it into a class file, you must use include_once; this ensures that you The file to be included will only be included once, and these two 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 tag:
Always use to define your php code instead of simply using , this will ensure PEAR compatibility , which is also conducive to cross-platform porting.

Comment statement 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 |

// | 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 to indicate the copyright, license, and author. etc. At the same time, add VIM’s MODELINE in 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 the original file. Similar expressions (such as "Last modified", etc.)

URL samples:
You can refer to RFC 2606 and use "www.example.com" as all URL samples.

Constant naming:
Constants should be in uppercase letters as much as possible. For ease of understanding, 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_STANDDARD file in PEAR. To better understand these coding rules, you can also refer to the existing PEAR core module code.

Start using PEAR extends PEAR{
Your class definition...
}




Of course, you need to abide by the coding rules of PEAR mentioned earlier, and then you can Your class internally implements what you want to do. 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: PEAR’s error handling base class. 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 of which are destructors and error handling

Destructor
PHP supports constructors, but does not support destructors, but , 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 take a look at PEAR Source code:
<br>function PEAR() { <br>if (method_exists($this, "_".get_class($this))) { <br>global $_PEAR_destructor_object_list; <br>$_PEAR_destructor_object_list[] = &&this; <br>} <br>if ($this->_debug) { <br>printf("PEAR constructor called, class=%sn", <br>get_class($this)) ; <br>} <br>..... <br>function _PEAR_call_destructors() { <br>global $_PEAR_destructor_object_list; <br>if (is_array($_PEAR_destructor_object_list) && sizeof($_PEAR_destructor_object_list)) { <br>reset ($_PEAR_destructor_object_list); <br>while (list($k, $objref) = each($_PEAR_destructor_object_list)) { <br>$destructor = "_".get_class($objref); <br>if (method_exists($ objref, $destructor)) { <br>$objref->$destructor(); <br>} <br>} <br>//Clear the registered object list, <br><br>//Prevent duplication Call<br><br>$_PEAR_destructor_object_list = array(); <br><br>} <br><br>} <br><br>.... <br>register_shutdown_function("_PEAR_call_destructors"); <br>




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. function, if there is one, then the reference of the current class will be put into a global list. In _PEAR_call_destructors, each element in the global list will be checked to see if there is a corresponding destructor. If so, it will be called. 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, so that 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 don’t just 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 Output error information, it also forces you to be in HTML form. You can output XML, CSV form, or other forms you define. You only need to derive a new class from PEAR_Error, and then create and "throw" it at the appropriate time. Just create an object of this new class.

Simple error handling:
In PEAR, the simplest error handling is to "throw" the error. You only need to simply create and return a PEAR_Error object.Here is a simple example:
<br>function myconnect($host = "localhost", $port = 1080) <br>{ <br>$fp = fsockopen($host, $port, $errno, $errstr); <br>if (!is_resource($fp)) { <br>return new PEAR_Error($errstr, $errno); <br>} <br>return $fp; <br>} <br><br>$sock = myconnect(); <br>if (PEAR::isError($sock)) { <br>print "connect error: ".$sock->getMessage()."<BR&gt ;n" <br>} <br>


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 get the latest error message. Note: Be sure to use PEAR::isError

in key places and 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 Processing mode, the latter is a wrapper function that returns a PEAR_Error object. It is slightly different from directly creating and returning a PEAR_Error object. If you omit parameters such as $mode, $options, etc., it will use default values ​​to create the PEAR_Error. Object, these default values ​​​​can be customized using setErrorHandling().

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, and can be the following constants:
PEAR_ERROR_RETURN: only returns the error object (default mode)
PEAR_ERROR_PRINT: prints 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 error and exit, the program terminates.
PEAR_ERROR_CALLBACK: Use a callback function or method to handle the current error and terminate the program.
$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, which 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.

Summary
This is the end of the introduction to PEAR. 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
Set up your error Handle patterns 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 requires PHP With the joint efforts of people in the community to improve it and enhance it, PHP will become more and more powerful.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/313979.htmlTechArticleYou may already be a PHP veteran and have 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 make...
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template