Use PEAR to write your next php program

Source: Internet
Author: User
Tags code tag php error
You may already be a veteran of PHP and have written a lot of very good code. However, if you want to add them to your current project, is it difficult? Your friend wants to use your code as a module in his project, but you find that you have used a completely different encoding style to adapt to it. it is better to rewrite it! Please come with me and use PEAR
You may already be a veteran of PHP and have written a lot of very good code. However, if you want to add them to your current project, is it difficult? Your friend wants to use your code as a module in his project, but you find that you have used a completely different encoding style to adapt to it. it is better to rewrite it!

Please come with me and use the PEAR standard to compile your PHP program. your program will be more dynamic, your programs and code will be easily integrated with other Masters' code. PEAR, like CPAN's for PERL, will make PHP generate higher energy.

What is PEAR?
PEAR is the abbreviation of the PHP Extension and Application Repository. It is a code repository for PHP extensions and applications. In short, PEAR is the CPAN of PHP.

Why PEAR?
PHP is a very good scripting language that is concise and efficient. with the release of 4.0, more and more people use it to develop dynamic websites. it can be said that, PHP has become one of the best INTERNET development languages. especially for website developers who need to develop small and medium-sized commercial applications quickly and efficiently, PHP is the 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 their code and applications as easily as those in the PERL community, because PHP lacks a unified code library like CPAN to classify and manage application code modules (everyone familiar with PERL knows that CPAN is a huge library of PERL extension modules, the written application modules can be placed under the appropriate category directory under CPAN. other users can easily reuse them. of course, you also need to follow the rules when writing the application module .)

To this end, PEAR came into being, and has been distributed along with the PHP core since 4.04.

What benefits does 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, others can easily retrieve and share your results.

2. PEAR is not only a code repository, but 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 two classes to implement functions such as destructor and error capture. you can use these functions through inheritance.

PEAR Encoding Rules
PEAR encoding rules include indentation rules, control structures, function calls, function definitions, comments, including code, PHP tags, file header comments, CVS tags, and URL samples, constant naming. The following is a brief introduction:

  • Indent rules:

    In PEAR, four spaces are required for code reduction, and TAB is 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, set indent-tabs-mode to nil.

    But you like to use (X) Emacs to edit php files like me, I strongly recommend you install PHP-MODE so that when you write PEAR code, it will automatically adjust your shrink style, of course PHP-MODE has many excellent features that you can download the latest PHP-MODE from the list of resources.

  • Control structure:

    The control structure mentioned here includes: if for while switch. For control structures, in keywords (such as if ..) leave a space box and then use parentheses to avoid confusion with function calls. In addition, you should try to use curly braces {} as far as possible {}, even if the syntax is optional. In this way, you can avoid logical doubts or errors when adding new code lines. 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 calling, the function name and left parenthesis (there should be no space between them. for function parameters, there must be the same space separation between the separated comma and the next parameter, there must be no space between the last parameter and the right brace. The following is a standard function call;

    $ Result = foo ($ param1, $ param2, $ param3); nonstandard syntax: $ result = foo ($ param1, $ param2, $ param3 ); $ result = foo ($ param1, $ param2, $ param3 );

    In addition, if you want to assign values to the results returned by the function, there must be spaces between the equal sign and the assigned variable. In addition, if you are using a series of related values, you should add appropriate spaces, align them like this:

                    $result1 = $foo($param1, $param2, $param3);                $var2    = $foo($param3);                $var3    = $foo($param4, $param5);                

  • Function definition:

    The 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 at the end of the parameter table and always return meaningful function values whenever possible.

  • Notes:

    Online documents of classes should be converted to PHPDoc, just like JavaDoc. PHPDoc is also an application of PEAR, more detailed introduction you can go to http://www.phpdoc.de/view. In addition to the online documentation of classes, we recommend that you use non-document comments to interpret your code. when you see a piece of code, consider: Oh, I don't need to describe it carefully in the document. So you 'd better make a simple comment on the code to prevent you from forgetting how it works. For the form of annotation, C's/**/and C ++'s // are both good. however, do not use Perl or shell's # annotation method.

  • Code included:

    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; this ensures that the files you want to include will only be contained once, and the two statements share the same file list, so you do not have to worry about confusion between the two statements. once require_once contains a file, include_once will no longer contain the same file, and vice versa.

  • PHP code tag:

    Always use Define your php code, instead of simply using This ensures PEAR compatibility and facilitates cross-platform migration.

  • Annotation declaration of the file header:

    All PHP code files that need to be included in the PEAR core release. at the beginning of the file, you must add the following comments:

                    /* vim: set expandtab tabstop=4 shiftwidth=4: */                // +----------------------------------------------------------------------+                // | PHP version 4.0                                                      |                // +----------------------------------------------------------------------+                // | Copyright © 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 not in the PEAR core code library, we recommend that you have such a comment block at the beginning of the file to indicate copyright, protocol, author, and so on. At the same time, we also add the vim modeline in the first line, so that we can maintain the PEAR code style in VIM.

  • CVS flag:

    As shown above, add the cvs id tag to each file. if this tag is not found in the edited or modified file, add it, or replace similar representations in the original file (such as "Last modified)

  • URL sample:

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

  • Constant name:

    Constants should be capitalized as much as possible. to facilitate understanding, use underscores to separate each word. At the same time, you should use the package name or class name where the constant is located as the prefix. For example, constants in the Bug class should start with Bug. The above are PEAR encoding rules. for detailed encoding rules, refer to the description of CODING_STANDDARD file in PEAR. To better understand these encoding rules, you can also refer to the code of the existing PEAR core module.

Start using PEAR

  • PEAR

    It's easy to use PEAR. you just need to define your own PEAR program as follows:

    Require_once "PEAR. php"; class your_class_name extends PEAR {your class definition ...}

    Of course, you need to follow the PEAR encoding 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 two predefined classes:
    PEAR: this is the base class of PEAR. all PEAR extensions must be derived from it.
    PEAR_Error: base class for processing PEAR errors. you can choose to derive your own error processing class.

    Generally, you should not directly create a PEAR instance, but instead derive a new class and then create an instance of the new class. As a base class, PEAR provides us with some useful functions, mainly including destructor and error handling.

    1. Destructor

      PHP supports constructor, but does not support destructor. However, PHP provides the register_shutdown_function () function, which can call back the registered function before the script ends. Therefore, PEAR uses this feature, simulation of destructor is provided. If you have a PEAR subclass called mypear, you can define a function in the mypear class. the function name is underlined and 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 will not be executed when the object is deleted, but at the end of the script. 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, you need to call the constructor of its parent class in your constructor, because PHP will not automatically call the constructor of the parent class, the Destructor needs to be registered in the PEAR constructor. let's look at the source code of PEAR:

                          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 = % sn", 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 () ;}// clear the list of registered objects, // prevent repeated calls $ _ PEAR_destructor_object_list = array ();}}.... register_shutdown_function ("_ PEAR_call_destructors ");

      The above code shows how PEAR implements the destructor. in the component functions, it checks whether there are Destructor in the current class, the reference of the current class will be placed in a global list. In _ PEAR_call_destructors, check whether each element in the global list has a corresponding destructor. If yes, then, the global list is cleared.

      In the last line of PEAR. php code, call register_shutdown_function ("_ PEAR_call_destructors") and register _ PEAR_call_destructors. in this way, PHP calls back this function when the script is executed. Using destructor, you can do some necessary "aftercare" work before processing user requests and exiting. a typical example is that you can close opened files, disconnect the database and save some data to the disk.

    2. Error handling

      PEAR allows you to handle errors in many ways. instead of simply returning an error code or message, you can return a PEAR_Error object, or a new error object derived from PEAR_Error.

      The error object in PEAR does not have a specific output format. it can only capture errors, not return too much information to users, or call back a special error processing function. at the same time, even if an error message is output, it forces you to use the HTML format. you can output XML, CSV format, or other custom formats, you only need to derive a new class from PEAR_Error, and then create and "throw" the object of this new class as appropriate.

  • Simple error handling:

    In PEAR, the simplest error handling method is "throw". you only need to create and return a PEAR_Error object. The following is a simple example:

                     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()."
    n" }
    As shown in the code above, after executing a piece of code that may produce errors, you need to use the PEAR isError to check for errors, you can use the getMessage of PEAR_Error to obtain the last error message. Note: You must use PEAR: isError in key areas.

  • Use raiseError

    After PHP4.0.5, PEAR has two more functions: setErrorHandling ($ mode, $ options = null) raiseError ($ message = null, $ code = null,
    $ Mode = null, $ options = null, $ userinfo = null)
    The former can set the default PEAR error handling mode, and the latter is a packaging function, which returns a PEAR_Error object, which is slightly different from the object directly created and returned PEAR_Error, if $ mode, $ options, and other parameters are omitted, the default value is used to create the PEAR_Error object. you can use setErrorHandling () to customize these default values.

  • PEAR_Error

    PEAR_Error is a base class of the PEAR error object. Unlike PEAR, you can directly create a PEAR_Error instance:
    $ 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: the processing mode of this error. the following constants can be used:
    • PEAR_ERROR_RETURN: returns only 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: trigger an error using PHP's trigger_error (). If you have set the error processing function or set the PHP error processing level to E_USER_ERROR, the current program will be terminated.
    • PEAR_ERROR_DIE: print the error and exit. The program is terminated.
    • PEAR_ERROR_CALLBACK: Use a callback function or method to handle the current error and terminate the program.
    • $ Options: this parameter takes effect only when $ mode is PEAR_ERROR_TRIGGER and PEAR_ERROR_CALLBACK. for PEAR_ERROR_TRIGGER, $ options must be E_USER_NOTICE, E_USER_WARNING, or E_USER_ERROR, the value is the same as that of trigger_error in PHP. If $ mode is PEAR_ERROR_CALLBACK, $ options can be a string with the name of the function to be called back, or an array of 2 elements, which is an object variable, and a string (indicating the method to be called ).
    • $ Userinfo: stores additional user information. you can put the relevant debugging information here.

    PEAR_Error has some common methods. these methods are not described in the PHP document and are listed here:

    • Int getMode: returns the current error processing mode, an integer.
    • String getMessage: returns the current complete error message, a string.
    • Mixed getCallback: returns the current callback information, which may be the name of the callback function or an array (object, method.
    • Int getCode: return the error code of the integer type.
    • String getType: the type of the returned error, that is, the current class name, string.
    • String getUserInfo: returns the additional user information, a string.
    • String getDebugInfo: the content is the same as above.
    • String toString: returns the detailed string description of the current object, including the error processing mode, level, error information, error code, and related callback functions.

Summary
Now, the PEAR introduction is complete. To sum up, if you want to create a PEAR extension application, you need:

  1. Require_once "PEAR. php"
  2. Use class your_pear_extend extends PEAR {} to define your new class.
  3. In your class constructor, call the constructor of the parent class PEAR:
                    function your_pear_extend{                $this->PEAR();                ...                }                
  4. Define your destructor _ your_pear_extend if needed
  5. If necessary, derive your own error handling class from PEAR_Error
  6. Set your error handling mode and trigger the error when appropriate.
  7. After executing code that may produce errors, use PEAR: isError ($ obj) to capture the corresponding errors.
  8. Implement your own functions.
In the latest PHP4.05 PEAR core release, there are already many excellent application modules, such as PHPDoc, Cache, HTML... of course, compared with CPAN, PEAR is just getting started. it requires the joint efforts of people in the PHP community to improve and enhance it so that PHP will become more and more powerful.

Related Resources
Pear homepage

PHP homepage

PHPDoc homepage, which can generate API documentation similar to JAVADOC from your PEAR application source code

PHP-Mode for XEmacs/Emacs, which provides php syntax support for emacs/xemacs and supports pear code style.

Vim homepage, a very good editor, and good support for php

Author profile
Pan Fan (Night Sailer): Beijing Saidi data Co., Ltd. engineer. Mainly engaged in data analysis and conversion, as well as related development work. He is good at using VB, PERL, PHP for development and cultural work in Linux. Recent interest is Perl, Php and XML applications, php mvc development mode, PERL-GTK use. You can contact him via E-mail: nightsailer@hotmail.com.

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.