PEAR: Common Modules

Source: Internet
Author: User
Tags expression getmessage glob sql naming convention net socket split
In the previous article, we introduced the concept of pear, coding rules, simple use method, you may have a preliminary understanding of it. This time, we'll introduce the functionality and usage of some of the modules in the existing Pear library.
First, naming convention
Before we get to the existing Pear module, let's take a look at how Pear organizes its classification and naming conventions. The modules in pear are organized in the same way as CPAN, and each module's related files are placed under its own category directory, and some are placed directly under the root directory of pear (a single file). Because Pear does not have a namespace like Java, so your class name should be able to reflect the relationship between your module name or the parent class name, keep a certain agreement, for example, your module name: "Mp3/common", then, your PHP file should be located in: mp3/common.php, The class name of your module should be: Mp3_common. In general, if your module is based on an existing module, it is recommended to put your existing module under the same directory. If you are designing a new class and module, you can create a new directory yourself, or put it under the same directory for similar purposes. For example, you have a new module for processing logs, it is recommended that you put it under the log/, the application module for log processing, if the new module is used to deal with MP3, then you can create a new directory MP3, placed under the MP3 directory.

Two, existing pear module
Since most of pear's modules are still under development, here is a list of the modules in pear that are published along with php4.05, and it should be noted that some abstract classes or base classes (such as mail.php,log.php,cache.php) are not enumerated. We're just focusing on modules that have specific functions. Here is a list of these modules:

Benchmark/timer Test your PHP code for operational efficiency
Benchmark/benchmark_iterate test the performance of a function when you loop through it
Cache/output can cache the output of your PHP script, you can cache it in a variety of ways (there are files, databases, or shared memory), if you use this module to increase the load on the server, so if you want to use the cache of dynamic scripts to provide efficiency, you might as well be using Zend Optimize, this module may not be suitable for
Cache/graphics can cache pictures that you need to dynamically output
Console/getopt the processing module of command line arguments
CMD a virtual shell that can be used to run some system commands
CRYPT/CBC implementation of Perl CRYPT::CBC module simulation
Crypt/hcemd5 to implement Perl CRYPT::HCE_MD5 module functions

DATE/CALC implementation date-related operations
The conversion of Date/human Human calendar
DB provides a unified, abstract database operation layer with back-end support for multiple databases
File/find File Lookup
FILE/PASSWD manipulate password classes of files, such as Password,httppass,cvspassword
File/searchreplace find a replacement string in a file
Html/form can quickly create a Form in HTML
html/it Implement template customization, dynamically generate the function of the page, similar to the template function in Phplib, but to be simple and easy to use
HTML/ITX implements extended IT capabilities to make your templates more flexible and more complex to operate
Html/processor xml_parser Extension so that it can be applied to HTML file operations
Http/compress a wrapper class for the PHP output buffering mechanism, while compressing and storing the buffered content
Image/remote without having to download the entire picture locally, you can get information about the image of the remote system.
Log/composite Horde an extension to the log abstract class to enable multiple log processing objects to obtain the same log event. Note that the following modules in the log directory are part of the Horde project, most of which are abstract superclass
Log/file writes log information to a file
Log/mcal sends information to the local or remote-mcal database of the schedule management software
A super class of observer in Log/observer Horder
Log/sql send log information to SQL database
Log/syslog send information to the syslog
mail/rfc822 Check if an email address is a legitimate rf822 email address
Mail/sendmail use SendMail to send letters
MAIL/SMTP use an SMTP server to send letters
Mathematical calculation of fractal in math/fraction processing
Math/util calculation GCD
Net/curl Object-oriented packaging for PHP's Curl extensions
Net/dig manipulating Dig for DNS-related query operations
NET/SMTP use Net/socket to implement SMTP protocol
Net/socket common socket class, realize the common socket operation of the packaging
The conversion of Numbers/roman and Roman numerals
Payment/verisign implementation and Verisign payment gateway interaction
Pear provides 2 basic classes of pear modules, pear and Pearerror classes
Pear/installer Pear's installation class, which provides functionality similar to the CPAN modules in Perl
PHPDOC automatically generate API documentation from PHP code
Schedule/at interacts with the at Daemon on Unix
Xml/parser XML parser based on PHP XML extensions
Xml/render the XML document into other formats (html,pdf), which is just an abstract class that already has the HTML implementation in the latest Pear CVS code
Xml/rpc an abstract class using PHP to implement XML-RPC, which has been implemented in the latest Pear CVS code xml/rpc/server

Introduction of Main module use
Now we will briefly introduce some of the more commonly used, and the function has been more complete and stable, can be used in the "actual Combat" module, which for several powerful modules DB,PHPDOC,XML_PARSER,IT,ITX will be introduced in future articles.

1.pear/installer
This module belongs to Pear's own core module, which completes the installation and maintenance of other pear modules, similar to the functions of the CPAN module in Perl, but at present only install functions, other such as query, check dependencies, etc. are not complete, pear itself is not similar cpan Such an open site, but with the growing number of developers involved in pear, everything will be there.

Using syntax: Pear_installer::installer ($file)
$file are module files that need to be installed, either local files or remote files, such as http://or ftp,installer, which are automatically downloaded to the local area. Files are typically packaged with gzip, including a package.xml file that describes the information about your module, such as the files involved, dependencies, and, of course, your module's PHP files. The Pacakage.xml DTD file is under the Pear directory, and the name is PACKAGE.DTD.

<?php
Require_once "pear/installer.php";
$installer = new Pear_installer;
Install the specified module
$result = $installer->install ($package _file);
if (Pear::iserror ($result)) {
echo "Install $package _file failed!";
}else {
echo "Install $package _file sucess!";
}
?>






2.CMD
Although most PHP applications rarely invoke system commands because they are web-based, they avoid calling system commands directly from operational efficiency and system load considerations, but in some special applications or when you are willing to use PHP as a shell tool, Calling existing system tools is inevitable. CMD allows you to easily execute a series of system commands.

Use syntax: SetOption ($option, $setting)
Set parameter $options to $setting

$options is a constant, which can be the following values:
Cmd_shutdown: Execute command via SHUTDOWN function
Cmd_shell: Specifies the path of the SHELL
Cmd_output: Whether the standard output of the Mask command
Cmd_nohup: Use NOHUP background to execute commands
Cmd_verbose: Print error to standard output



Command ($command)
Add the command you want to execute, $command can be an array or an ordinary string

EXEC ()
Execute the command you have added

<?php
Require_once "cmd.php";
$cmd = new cmd;
$cmd->command (' Tar zcvf test.tar.gz ~/test ');
if ($cmd->exec ()) {
echo "success! \ n ";
} esle {
echo "Error:". $cmd->lasterror;
}
?>





3.benchmark/timer and Benchmark/iterate
These 2 modules let you test how efficient your code is, and I think it's useful for system debugging: You can try different algorithms, look at the time each algorithm needs to run, and then choose the best way. Benchmark/timer the time difference between the 2 different points in the test run, Benchmark/iterate is the timer extension, and the times required to run a piece of code (function) n times.

Using syntax: Benchmark/timer

Timer::setmarker ($name) sets the current point of time to $name
Timer::start () Start test
Timer::stop () Stop testing
timer::timeelapsed ($start = ' start ', $end = ' Stop ') calculates the time difference between $start and $end at 2 points
Timer::getprofiling () returns the elapsed time between start and stop
<?php
Require_once "benchmark/timer.php";
$timer = new Benchmark_timer;

$timer->start ();
$timer->setmarker (' Marker 1 ');
$timer->stop ();

$profiling = $timer->getprofiling ();
?>





Benchmark/iterate

Iterate::run ()
Loops through the specified function. This is a method with variable parameters, the first parameter is the number of times to loop, the 2nd parameter is the function to execute, and the 3rd parameter is the argument to pass to the test function.

Iterate::get ()
Returns the time that the test took

<?php
Require_once "benchmark/iterate.php";

$benchmark = new Benchmark_iterate;

function foo ($string)
{
Print $string. "
";
}
$benchmark->run (+, ' foo ', ' Test ');
$result = $benchmark->get ();
?>





3.file/find
&glob ($pattern, $dirpath, $pattern _type= ' php ')
Search for directories and files that match $pattern in $dirpath, and return matching files and directories array groups

&search ($pattern, $directory, $type = ' php ')
Searches in $directory for files that conform to the $pattern rule, returning a matching array of file names (note that only files, excluding subdirectories). $pattern is the search condition to be specified, typically a regular expression, $patten _type specifies the pattern of the rule expression, the default is PHP mode, and you can also specify "Perl" to use the Perl pattern's regular expression

Hint: Search and Glob are different, Glob does not recursively search subdirectories, and search recursively searches subdirectories.

<?php
Require_once "file/find.php";
$find = new File_find;
Search current Directory
$php _files = $find->glob ("*php", ".");
if (Pear::iserror ($php _files)) {
Die "Error:". $php _files->getmessage (). " \ n ";
}
Recursively search the current directory
$all _php_files = $find->search ("*php", ".");
if (Pear::iserror ($all _php_files)) {
Die "Error:". $php _files->getmessage (). " \ n ";
}
?>





4.file/passwd
Manipulates files in password format, similar to the PServer password files of the. Htppass,cvs of standard Unix password,apache. From the existing version of the code, it is not really used to maintain these passwd files (for example, do not support shadow). However, you can use it to create a similar password file, of course, security is not very high.

How to use:
FILE_PASSWD ($file, $lock =0)----------Create the object, $file is the Passwd file you want to manipulate, $lock specify whether to lock the file with flock.
AddUser ($user, $pass, $cvsuser)----------Add a user, $user, $pass is the user name and password, $cvsuser is the ID of the CVS user
Moduser ($user, $pass, $cvsuser)----------modify $user password to $pass, $cvsuser is the ID of the CVS user
Deluser ($user)----------Delete the specified user $user
VerifyPassword ($user, $pass)----------Verify user password
Close ()----------Save the changes to the password file, turn off the password file, and unlock the file.
5.file/searchreplace
Find and replace strings in a file

How to use: File_searchreplace ($find, $replace, $files, $directories = ', $include _subdir = 1, $ignore _lines = Array ())

Building and setting objects

$find
The string to find, either a string or a regular expression

$replace
The string to be replaced, which can be a string or a regular expression

$files
Specifies which files are substituted, or a string separated by ","

$directories
Specifies an action in that directory, optional, array, or a string that is split by ","

$include _subdir
If you are working in a directory, specify whether to recursively perform the above actions in a subdirectory, which can be a value of 1 or 0.

$ignore _lines
Specifies the line of files to ignore, which is an array, and any file rows that start with any string in the array are ignored.

Getnumoccurences ()
Returns the number of times a lookup replacement has been performed

GetLastError ()
Returns the last error message

Setfind ($find)
Set the string to find

Setreplace ($replace)
Set the string to replace

Setfiles ($files)
Set up files to perform a replacement operation

Setdirectories ($directories)
Set up a directory to replace operations

Setincludesubdir ($include _subdir)
Set whether find substitution is also performed in subdirectories

Setignorelines ($ignore _lines)
Set the rows to ignore, only when using the "normal" search function

Setsearchfunction ($search _function)
Set the search function you want to use, which can be the following parameters:

Normal default value, reads the contents of the file using the filename function, and replaces it with Str_replace line by row.
Quick replaces the entire file directly with Str_replace
Preg use Preg_replace () to replace, you can use regular expressions that meet the requirements of this function
Ereg use Ereg_replace () to replace, you can use regular expressions that meet the requirements of this function



Dosearch ()
Perform a Find-and-replace operation

<?php
Require_once "file/searchreplace.php";
Require_once "File/find";

Recursively search the current directory
$find = new File_find;
$all _php_files = $find->search ("*php", ".");
if (Pear::iserror ($all _php_files)) {
Die "Error:". $php _files->getmessage (). " \ n ";
}
if (!count ($all _php_file)) {
Die "NO php source files found!\n";
}
Revise the PHP logo to <?php to conform to the pear standard
$replace = new File_searchreplace (';? ', ' <?php ', $all _php_files);
$replace->dosearch ();
if ($replace->getlasterror ()) {
Die "error occurred:". $replace->getlasterror ();
} else {
echo "was replaced with a total success". $replace->getnumoccurences (). Secretariat \ n ";
}
?>





6.html/form
This module allows you to quickly generate a submitted form without having to rewrite the HTML code

How to use: Form::html_form ($action, $method = ' get ', $name = ', $target = ')

The constructors for this class have parameters that are basically consistent with the form parameters that are typically written in the HTML code, $action the URL to be submitted to in the form, $name can specify the name of the form, $target specify whether to open a new window, and so on.

The following Addxxx series method is used to add the corresponding control to the form, and the control's properties are consistent with the HTML.
AddText ($name, $title, $default, $size = html_form_text_size)
AddCheckBox ($name, $title, $default)
Addtextarea ($name, $title, $default, $width = html_form_textarea_wt, $height = html_form_textarea_ht)
Addpassword ($name, $title, $default, $size = html_form_passwd_size)
Addsubmit ($name = "Submit", $title = "Submit Changes")
Addreset ($title = "Discard Changes")
Addselect ($name, $title, $entries, $default = ', $size = 1, $blank = ', $multiple = false, $attribs = ')
Addradio ($name, $title, $value, $default)
AddImage ($name, $SRC)
Addhidden ($name, $value)

Display ()
Show this form

<?php
Require_once "html/form.php";
Create and display a login form
$myform = new Html_form ("./login.php");
$myform->addtext (' username ', ' username ', ');
$myform->addpasswd (' passwd ', ' login password ', 20);
$myform->addhidden (' Retry ', ' 1 ');
$myform->addsumit (' login ', ' log in ');
$myform->display ();
?>





7.mail/rfc822
It's not easy to check if an incoming email is legal, but you might try some regular expressions to check it, but it's not so convenient and efficient. Now, if you want to check whether a series of mailing addresses meet the RFC822 standards and split them into separate email addresses, you can try this module, very simple and practical.

How to use: mail_rfc822 ($address = null, $default _domain = null, $nest _groups = null, $validate = NULL)

Class constructor, $address is the list of addresses you want to verify, $default _domain, specify the default domain name or hostname, $nest _groups whether to group in the output, to display the $validate Do you need to verify that each atom parseaddresslist ($address = null, $default _domain = null, $nest _groups = null, $validate = NULL) parse validates the address list given, if The address is valid, returns a separate address list after the split, and returns an error message if an error occurs.

<?php
Require_once "mail/rfc822.php";
$RF 822 = new mail_rfc822;
$result = $rf 822->paseaddresslist (' who;whoim@hotmail.com;test@test.ch ');
if ($rf 822->error) {
echo "Error: $result";
}else {
Reset ($result);
For ($i =0 $i < count ($result); $i + +) {
echo "Email: $result [$i]\n";
}
}
?>





8.mail/sendmail
SendMail is the most commonly used MTA on Unix/linux, which allows you to send letters directly using SendMail

How to use: Mail_sendmail ($params)

Class constructor, $params is an associative array, you can set SendMail parameters, only ' Sendmail_path ' is currently valid, to set SendMail path Send ($recipients, $headers, $body) Send a letter, $recipients is your recipient's email address, can be a single, can also be used, separated address list, as long as the RFC82 standards can be met. $headers is the letterhead you send a letter to, which is a relational number of rents, the keyword of the array is the name of the letterhead (such as subject), and the array value is the value of the letterhead (for example: hello!). After processing the letterhead will be: subject:hello! $body is the letter body of the letter, including all the MIME-encoded parts. If successful, returns TRUE, otherwise returns a Pear_error object

<?php
Require_once "mail/sendmail.php";
$sendmail = new Mail_sendmail (Array (' sendmail_path=> '/usr/local/bin/sendmail '));
$header = Array (' Subject ' => ' Hello ', ' BCC ' => ' test2@hotmail.com ');
$body = ' This are a test message from nightsailer.com ';
$result = $sendmail->send (' test@nightsailer.com ', $header, $body);
if (Pear::iserror ($result)) {
echo "}else {
echo "}
?>





9.mail/smtp
For some sites now do not allow the use of sendmail, then if your PHP program want to use the letter function, you need to be able to use the external SMTP server to complete the corresponding functions.

How to use: Using this module and Mail::sendmail is basically the same. Note: This module requires the use of NET::SMTP modules: Mail_smtp ($params)
Valid parameters for $params are:
Server address for ' host ' smtp, default is localhost
' Port ' SMTP service port, default is 25
' Auth ' SMTP requires authorization verification, default is False
' Usename ' SMTP authorized user name
' Password ' SMTP-licensed password

Send ($recipients, $headers, $body)
Send

<?php
Require_once "mail/sendmail.php";
$params =array (' Host ' => ' smtp.nightsailer.com ', ' auth ' =true,
' username ' => ' night ', ' Password ' => ' 123456 ');
$sendmail = new Mail_sendmail ($params);
$header = Array (' Subject ' => ' Hello ', ' BCC ' => ' test2@hotmail.com ');
$body = ' This are a test message from nightsailer.com ';
$result = $sendmail->send (' test@nightsailer.com ', $header, $body);
if (Pear::iserror ($result)) {
echo "}else {
echo "}
?>





10.schedule/at
This module provides the interface of the at program above UNIX

Add ($cmd, $timespec, $queue = False, $mail = False)
Append an AT command

This method will generate a custom job for the at program:
$cmd is the program or script you want to run
$timespec is the time at which the job starts executing, in the same format as the at requirement
$queue an optional parameter that indicates the queue name of the job
$mail An optional parameter indicating whether to send an email report running results after the job is finished

Show ($queue = False)
The command displayed in the at queue returns an associative array whose key is the number of the job, and the corresponding key value is an associative array (runtime,queue) $queue is an optional parameter that you can use to qualify only the queue name match in the queue. Job list for queue

Remove ($job = False)
Deletes the specified at job $job from the at queue is the job number to delete, if successful, returns TRUE, otherwise returns false

<?php
Require_once "schedule/at.php";
$at = new Schedule_at ();
Generate and append a job
$result = $at->add (' Find/-type file-name core-exec rm-f {} \; ', ' 00:00 ');
if (Pear::is_error ($result)) {
Echo cannot append the job! \ n ";
echo "Reason: $result->getmessage () \ n";
Exit
}
Displays the current at queue
$queue = $at->show ();
if (Pear::iserror ($queue)) {
echo "An error has occurred! \ n ";
echo "Reason:". Queue->getmessage (). "\ n";
Exit
}
Reset ($queue);
while (the list ($job, $cmd) = each $queue) {
echo "[$job]". $cmd [' Runtime ']. "-". $cmd [' queue '];
echo "\ n"
}
?>





These are the uses of some pear modules, which require you to see the source files for these modules in more detail, or you can use Phpdoc to automatically generate the API documentation for these modules. We will discuss the phpdoc in detail in the next chapter.

IV. Resources
Pear CVS You can get the latest pear source from here
Hoder Project
PHPDOC Home



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.