Home  >  Article  >  Backend Development  >  PHP's treasure house directory PEAR

PHP's treasure house directory PEAR

不言
不言Original
2018-04-09 16:20:232217browse

This article introduces to you the treasure directory of PHP, PEAR. I share it with you here. Friends in need can refer to 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 PEAR
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 website developers who need to be able to develop small and medium-sized commercial applications quickly and efficiently. However, with the increasing number of PHP applications, there is a lack of unified standards and effective management of 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 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 very convenient 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 since 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, the 11 aspects of constant naming. The following 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 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 a value to the return result of the function, there must be a space between the equal sign and the assigned variable. Also, 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 comment forms, C's /* */ and C's // are both good, but 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 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 need 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 tags:
Always use bb9bd6d87db7f8730c53cb084e6b4d2d to define your php code, instead of simply using b26da186e11666e6dd99f28d6205715c, this can 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 like this at the beginning of the file, indicating copyright, agreement, 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, 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 code of the existing PEAR core module.

Start using PEAR

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 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 ones are destructor and error handling

Destructor
PHP支持构造函数,但是并不支持析构函数,不过,PHP提供register_shutdown_function()这个函数,从而能够在脚本终止前回调注册的函数,因此PEAR利用这个特性,提供了析构函数的仿真。假如你有一个PEAR的子类,叫做mypear,那么在mypear类中,你可以定义一个函数,函数名是下划线加上你的类名,_mypear(),这个函数就是这个类的析构函数。不过这个析构函数和C++中的析构函数不太一样,它不会在对象被删除的时候执行,而是在脚本结束的时候,毕竟这只是一个仿真。由于是使用了register_shutdown_function(),所以在你的析构函数里,打印的信息将不会返回浏览器中。此外,在你的构造函数中,需要调用一下它的父类的构造函数,因为PHP不会自动调用父类的构造函数,而析构函数需要在PEAR的构造函数中注册,我们可以看看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 (list($k, $objref) = each($_PEAR_destructor_object_list)) { 
$destructor = "_".get_class($objref); 
if (method_exists($objref, $destructor)) { 
$objref->$destructor(); 
} 
} 
//清空已注册的对象列表, 

//防止重复调用 

$_PEAR_destructor_object_list = array(); 

} 

} 

.... 
register_shutdown_function("_PEAR_call_destructors"); 
</code>



上面这段代码展示了PEAR是如何实现析构函数的,在构件函数中,将检查当前类中是否有析构函数,如果有,那么将把当前类的引用放入一个全局列表中,在_PEAR_call_destructors中,则检查这个全局列表中的每个元素是否存在相应的析构函数,如果有,则调用它,最后将全局列表清空。

在PEAR.php的最后一行代码,则调用register_shutdown_function("_PEAR_call_destructors"),注册_PEAR_call_destructors,这样,当脚本执行完毕的时候,PHP会回调这个函数。使用析构函数,你可以在处理完用户的请求,退出之前做一些必要的"善后"工作,典型的例子是,你可以关闭打开的文件,断开数据库的连接,将某些数据存入磁盘等等。

错误处理
PEAR中可以让你有很多的方式来处理错误,你不仅仅是简单地返回一个错误代码,或者错误的信息,而是可以返回一个PEAR_Error对象,或者是由PEAR_Error派生出来的新的错误对象。

PEAR中的错误对象的并没有限定具体的输出形式,它可以仅仅是捕获错误,不给用户返回太多的信息,也可以是去回调一个特殊错误处理函数,同时,即使输出错误信息,它也强迫你必须要是HTML形式,你可以输出XML,CSV形式,或者是其他你自己定义的形式,你只需要从PEAR_Error派生一个新的类,然后在适当的时候创建并"抛出"这个新类的对象就可以了。

简单的错误处理:
在PEAR中,最简单的错误处理是"抛出"这个错误,你只要简单地创建并返回一个PEAR_Error的对象就可以了。下面是一个简单的例子:

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

如上面代码所展示的,在执行一段可能产生错误的代码后,你需要使用PEAR的isError来检测是否存在错误,并且可以使用PEAR_Error的getMessage来取得最近一次的错误信息。注意:一定要在关键的地方使用使用PEAR::isError

使用raiseError

PHP4.0.5以后,PEAR多了2个函数:
setErrorHandling($mode, $options = null)
raiseError($message = null, $code = null, $mode = null,$options = null, $userinfo = null)


前者可以设置PEAR缺省的错误处理模式,后者是一个包装函数,返回一个PEAR_Error的对象,和直接创建并返回PEAR_Error的对象略有不同的是,如果省略$mode,$options等参数,它会使用缺省值来创建这个PEAR_Error的对象,这些缺省值你可以使用setErrorHandling()来定制。

PEAR_Error
PEAR_Error是PEAR的错误对象的一个基类,和PEAR不同,一般来说,你可以直接创建PEAR_Error的实例,创建方式:
$error = new PEAR_Error($message, $code, $mode, $options, $userinfo);

$message是你的错误信息,$code是该错误的错误号,后3个参数是紧密联系的:
$mode:是这个错误的处理模式,可以下列常量:
PEAR_ERROR_RETURN:仅仅返回该错误对象(缺省方式)
PEAR_ERROR_PRINT:在构建函数中打印这个错误信息,但是当前程序会继续运行。
PEAR_ERROR_TRIGGER:使用PHP的trigger_error() 触发一个错误,如果你已经设置了错误处理函数,或者你把PHP的错误处理级别设置为E_USER_ERROR,那么当前程序将会被终止。
PEAR_ERROR_DIE:打印错误并退出,程序终止。
PEAR_ERROR_CALLBACK:使用一个回调函数或者方法来处理当前错误,程序终止。
$options:这个参数只有在$mode是PEAR_ERROR_TRIGGER和PEAR_ERROR_CALLBACK的时候才起作用,如果是PEAR_ERROR_TRIGGER,$options必须是E_USER_NOTICE, E_USER_WARNING 或 E_USER_ERROR这3个常量的一个,同PHP中trigger_error的值一致。如果$mode是PEAR_ERROR_CALLBACK,$options可以是一个字符串,内容是要回调的函数名,也可以是一个2元素的数组,分别是一个对象变量,和一个字符串(标明要调用的方法)。
$userinfo:存放附加的用户信息,你可以把相关的调试信息放在这里。

PEAR_Error中有一些常用的方法,这些方法在PHP文挡没有描述,这里一一列出:

int getMode:返回当前的错误处理模式,整型。
string getMessage:返回当前完整的错误信息,字符串。
mixed getCallback:返回当前的回调信息,可能是所回调的函数名,或者是(对象,方法)的数组。
int getCode:返回整型的错误代码。
string getType:返回错误的类型,也就是当前的类名,字符串。
string getUserInfo:返回附加的用户信息,字符串。
string getDebugInfo:内容同上。
string toString:返回当前对象的详细字符串描述,内容包括错误处理的模式,级别,错误信息,错误代码,相关回调函数等等。

总结
至此,对于PEAR的介绍就结束了。概括地说,如果你要做一个PEAR的扩展应用,需要这么做:

require_once "PEAR.php"
使用class your_pear_extend extends PEAR{}定义你的新类。
在你的类的构造函数中,调用父类PEAR的构造函数:
function your_pear_extend{

$this->PEAR();

...
}



如果需要,定义你的析构函数 _your_pear_extend
如果需要,从PEAR_Error派生出你自己的错误处理类
设置你的错误处理模式,并在适当的时候触发错误。
在执行可能产生错误的代码后,用PEAR::isError($obj)捕获相应的错误。
实现你自己的功能。
在最新的PHP4.05的PEAR核心发布里,已经有不少优秀的应用模块了,比如:PHPDoc,Cache,HTML...当然,相对于CPAN来说,PEAR只是刚刚起步,需要PHP社区的人们的共同努力,来完善它,增强它,PHP才会越来越强大。


The above is the detailed content of PHP's treasure house directory PEAR. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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