Home > php教程 > PHP开发 > Use PEAR to write your next PHP program

Use PEAR to write your next PHP program

高洛峰
Release: 2016-11-29 09:58:57
Original
1107 people have browsed it

Introduction to pear: Use pear to write your next php program


Content:

What is pススar
Why should you use pススar?
ppススWhat benefits can
ppスス bring to me?
p・arEncoding rules
Start using ppear
Summary
Related resources

About the author



Pan Fan (night sailer) (nightsailer@hotmail.com)
Beijing Saidi Network Information Technology Co., Ltd.
June 2001
You may I am already a veteran of PHP 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 pear standard. Your program will have greater vitality. Your program and code will be easily integrated with other experts' codes. Pear is like cpan The same as for perl, which will cause php to generate higher energy.
What is pススr
pススr is the abbreviation of php extension and application repository (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 commercial applications quickly and efficiently, PHP is their preferred language. 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 It is 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.
ppススWhat benefits can
ppスス bring to me?
1. As mentioned before, 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 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.
Pea's coding rules
pear's coding rules include indentation rules, control structures, function calls, function definitions, comments, including code, php tags, comment blocks in file headers, cvs tags, url samples, constant naming these 11 aspect. Here is a brief introduction:
Indentation rules:
Pear needs to use 4 spaces to indent the code, and tabs are not 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 There are many great features, and you can download the latest version of php-mode from the resources 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 calls:
For function calls, there should be no space between the function name and the opening bracket ( (, and for function parameters, there should be the same space separation between the delimiting comma and the next parameter, the last There cannot be a space between the parameter and the right bracket. 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, 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 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 should be at the end of the parameter list, and always try to return meaningful function values.
About 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.
Include 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 include 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:
Use at all times to define your php code instead of simply using . This can ensure pear compatibility and facilitate 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.netso 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 like this 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 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_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 pスar
pear
Using pear is very simple, you only 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 above, 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 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 of which are destructors and error handling
Destructor
php supports constructors, but does not support destructors. However, PHP provides register_shutdown_function() function, so that it can call back the registered function before the script terminates, so 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 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 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:
<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>/ /Prevent repeated calls<br>$_pear_destructor_object_list = array();<br>}<br>}<br>....<br>register_shutdown_function("_pear_call_destructors");<br>


The above code shows how pear implements destructuring Functional, in the component function, it will check whether there is a destructor in the current class. If there is, then the reference of the current class will be put into a global list. In _pear_call_destructors, each item in this global list will be checked. Whether there is a corresponding destructor for the element, if so, it is called, and finally the global list is cleared.
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 not only simply return an error code, or error information, but you can return a pear_error object, or a new one derived from pear_error. Error object.
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 the error message is output, it It also forces you 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. The object is fine.
Simple error handling:
In pear, the simplest error handling is to "throw" the error. You just 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>$sock = myconnect();<br>if (pear::iserror($sock) ) {<br>print "connect error: ".$sock->getmessage()."<br>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 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, and directly creates and returns The pear_error object is slightly different in that if parameters such as $mode and $options are omitted, 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. Different from pear, generally speaking, you can directly create an instance of pear_error. The creation method is:
$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 processing mode of this error, and can be the following constants:
pear_error_return : Just return 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, then 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 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.
pear_error has some commonly used methods, 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
At this point, 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
Derive your own error handling class from pear_error if necessary
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 functions.
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 has just started and needs the help of the php community. With people's joint efforts to improve it and enhance it, php will become more and more powerful.
Related resources
pear homepage
php homepage
phpdoc homepage, 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 support pear well Code style
vim homepage, a very good editor, also has good support for php


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 Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template