In the previous article, we introduced the concept of PEAR, coding rules, and simple usage methods. You may have a preliminary understanding of it. This time, we will introduce the functions of some modules in the existing PEAR library and its use.
1. Naming Convention Before understanding the existing pear module, let’s first understand PEAR’s organizational classification and naming convention. The organization of modules in PEAR is similar to CPAN. The relevant files of each module are placed under its own category directory, and some are placed directly under the root directory of pear (single file). Since PEAR does not have a name space like Java, your class name should reflect the relationship between your module name or parent class name and adhere to certain conventions. For example, your module name: "Mp3/common", then , your php file should be located at: Mp3/common.php, and the class name of your module should be: Mp3_common. Generally speaking, if your module is improved from an existing module, it is recommended to put your module and the existing module in the same directory. If you are designing a new class or module, you can create a new directory yourself, or place them in the same directory for similar purposes. For example, if you write a new module for processing logs, it is recommended that you put it under Log/, indicating that it is an application module for Log processing; if the new module is used for processing MP3, then you can create A new directory mp3 is placed under the mp3 directory.
2. Existing PEAR modules Since most of Pear's modules are still under development, here are the modules in pear released with php4.05. It should be noted that some abstract classes or base classes ( Such as Mail.php, Log.php, Cache.php) are not listed, we only focus on modules with specific functions. The following is a list of these modules:
Benchmark/Timer tests the running efficiency of a piece of your PHP code
Benchmark/Benchmark_Iterate tests the performance of a function when it is executed in a loop
Cache/Output can cache the output of your php script. It can be cached in a variety of ways (in files, databases or shared memory). If you use this module, it may increase the load on the server, so if you want to pass To improve efficiency by caching dynamic scripts, you might as well use Zend optimize. This module may not be suitable.
Cache/Graphics can cache the images you need to dynamically output
Console/Getopt command line parameter processing module
CMD is a virtual shell that can be used to run some system commands.
Crypt/CBC implements simulation of the Perl Crypt::CBC module
Crypt/HCEMD5 implements the functions of the Perl Crypt::HCE_MD5 module
Date/Calc implements date-related operations
Date/Human Human Calendar Conversion
DB provides a unified and abstract database operation layer, and the backend supports multiple databases.
File/Find file search
File/Passwd manipulates password-like files, such as password, httppass, cvspassword
File/SearchReplace Find and replace a string in a file
HTML/Form can quickly create forms in html
HTML/IT implements template customization and dynamically generates pages, similar to the template function in phplib, but it should be simple and easy to use
HTML/ITX implements extended functions for IT, allowing you to customize your templates more flexibly and achieve more complex operations.
Extension of HTML/Processor XML_Parser so that it can be applied to the operation of html files
HTTP/Compress is a wrapper class for Php's output buffering mechanism, which can also compress and store the buffered content.
Image/Remote can obtain the image information of the remote system without downloading the entire image locally.
Log/composite Horde is an extension of the log abstract class that enables multiple log processing objects to obtain the same log event. Note that the modules under the Log directory are all part of the Horde project, and most of them are abstract super classes.
Log/file writes log information to a file
Log/mcal sends information to the database of local or remote schedule management software-mcal
A superclass of Observer in Log/observer Horder
Log/sql sends log information to the sql database
Log/syslog sends information to syslog
Mail/RFC822 Checks whether an email address is a valid rf822 email address
Mail/sendmail Use sendmail to send letters
Mail/smtp uses smtp server to send letters
Math/Fraction handles mathematical calculations of fractals
Math/Util calculates the greatest common divisor
NET/Curl is an object-oriented wrapper for PHP's Curl extension.
NET/Dig manipulates dig to perform dns-related query operations
NET/SMTP uses NET/Socket to implement the SMTP protocol
NET/Socket universal Socket class that implements packaging of commonly used socket operations
Numbers/Roman Conversion between Arabic numerals and Roman numerals
Payment/Verisign implements interaction with Verisign payment gateway
Pear provides two basic classes of the Pear module, PEAR and PEARError classes
PEAR/Installer The pear installation class provides similar functions to the CPAN module in Perl.
PHPDoc automatically generates API documentation from php code
Schedule/at interacts with the AT daemon on Unix
XML/Parser is an xml parser based on php's xml extension.
XML/Render generates xml documents into other formats (html, pdf). This is just an abstract class. There is already an implementation of html in the latest pear cvs code.
XML/RPC uses php to implement an abstract class of xml-rpc. In the latest pear cvs code, there is already an implementation of xml/RPC/Server.
3. Introduction to the use of main modules. Now we will briefly introduce some of the more commonly used ones and their functions. It is relatively complete and stable and can be used in "practical" modules. Several powerful modules such as Db, phpdoc, XML_Parser, IT, and ITX will be introduced separately in future articles.
1.PEAR/Installer
This module is the core module of pear itself. It completes the installation and maintenance of other modules of pear. It is similar to the function of the cpan module in perl. However, it currently only has the install function. Others such as querying, checking dependencies, etc. have not been completed. Pear itself There is no open site like cpan, but as the number of developers participating in pear continues to increase, everything will be there.
Usage syntax: PEAR_Installer::installer($file)
$file is the module file that needs to be installed. It can be a local file or a remote file, such as http:// or ftp. The installer will automatically download it locally. Files are generally packaged using gzip, which must include a package. The DTD file of pacakage.xml is under the pear directory, and its 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 call system commands, because these applications are based on the web, from the perspective of operating efficiency and system load, direct calls to system commands should be avoided. However, in some special applications or if you are willing to When PHP is used as a shell tool, it is inevitable to call existing system tools. CMD allows you to easily execute a series of system commands.
Usage syntax: setOption ($option, $setting)
Set parameter $options to $setting
$options is a constant, it can be the following values:
CMD_SHUTDOWN: Execute commands through shutdown function
CMD_SHELL: Specify the path of the shell
CMD_OUTPUT: Whether to block the standard output of the command
CMD_NOHUP: Use nohup to execute commands in the background
CMD_VERBOSE: Print errors to standard output
command($command)
Add the command that needs to be executed. $command can be an array or an ordinary string
exec()
Execute the added command
<?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 allow you to test how efficiently your code runs, which I think is useful for system debugging: you can try different algorithms, carefully examine how long each algorithm takes to run, and then choose the best way. Benchmark/Timer tests the time difference between two different time points during operation. Benchmark/Iterate is an extension of Timer to test the time required to run a certain piece of code (function) n times.
Usage syntax: Benchmark/Timer
Timer::setMarker($name) sets the current time point to $name
Timer::start() starts testing
Timer::stop() stops testing
Timer::timeElapsed($start = 'Start', $end = 'Stop') Calculate the time difference between $start and $end.
Timer::getProfiling() returns the time elapsed 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()
Runs the specified function in a loop. This is a method with variable parameters. The first parameter is the number of times to loop, the second parameter is the function to be executed, and the third parameter onwards are the parameters to be passed to the test function.
Iterate::get()
Returns the time taken by the test
<?php
require_once "Benchmark/Iterate.php";
$benchmark = new Benchmark_Iterate;
function foo($string)
{
print $string."
";
}
$benchmark->run(100, 'foo', 'test');
$result = $benchmark->get();
?>
3.File/Find
&glob ($pattern, $dirpath, $pattern_type='php')
Search directories and files matching $pattern in $dirpath and return an array of matching file and directory names
&search ($pattern, $directory, $type='php')
Search $directory for files that match $pattern rules and return an array of matching file names (note, only files, not subdirectories). $pattern is the search condition to be specified, usually a regular expression. $patten_type specifies what mode of regular expression to use. The default is php mode. You can also specify "perl" to use the regular expression of perl mode.
Tip: search Unlike glob, glob does not search subdirectories recursively, while search searches subdirectories recursively.
<?php
require_once "File/Find.php";
$find = new File_Find;
//Search the 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
Manipulate files in password format, similar to standard unix password, apache's .htppass, and cvs' pserver password files. Judging from the current version of the code, it cannot really be used to maintain these passwd files (for example, shadow is not supported). But you can use it to create a similar password file, of course, the security will not be very high.
How to use:
File_Passwd($file,$lock=0)----------Create an object. $file is the passwd file you want to operate. $lock specifies whether to use flock to lock the file.
addUser($user,$pass,$cvsuser)----------Add a user, $user, $pass are the user name and password respectively, $cvsuser is the ID of the cvs user
modUser($user,$pass,$cvsuser)----------Change the password of $user 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 just now to the password file, close the password file, and unlock the file.
5.File/SearchReplace
How to
find and replace strings in files
: File_SearchReplace($find, $replace, $files, $directories = '', $include_subdir = 1, $ignore_lines = array())generates and sets the object
$find
The string to find, which can be a string or a regular expression
$replace
The string to be replaced with, which can be a string or a regular expression
$files
Specify which files to perform the replacement operation in, an array or a string separated by ","
$directories
Specify the directory to operate in, optional, an array or a string separated by ","
$include_subdir
If operating in a directory, specifies whether to perform the above operation recursively in subdirectories, which can be a value of 1 or 0.
$ignore_lines
Specify the file lines to be ignored. This is an array. Any file lines starting with any string in this array will be ignored.
getNumOccurences()
Returns the number of times a search and replace has been performed
getLastError()
Return the last error message
setFind($find)
Set the string to be found
setReplace($replace)
Set the string to be replaced
setFiles($files)
Set the file to be replaced
setDirectories($directories)
Set the directory to be replaced
setIncludeSubdir($include_subdir)
Set whether to also perform search and replace in subdirectories
setIgnoreLines($ignore_lines)
setSearchFunction($search_function)
only when using the "normal" search function
Set the search function to be used, which can be the following parameters:
normal Default value, use the file function to read the file content, and then use str_replace to replace it line by line.
quick uses str_replace to directly replace the entire file
preg uses preg_replace() to replace, you can use regular expressions that meet the requirements of this function
ereg uses 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";
}
//Correct the php flag of <? to <?php to comply with the pear standard
$replace = new File_SearchReplace('<? ','<?php ',$all_php_files);
$replace->doSearch();
if ( $replace->getLastError() ) {
die "An error occurred:" . $replace->getLastError();
} else {
echo "A total of " . $replace->getNumOccurences() . " has been successfully replaced. n";
}
?>
6.HTML/Form
This module allows you to quickly generate a submission form without having to rewrite the HTML code.
Usage: Form::HTML_Form($action, $method = 'GET', $name = '', $target = '' )
The constructor of this class has some parameters, which are basically the same as the form parameters usually written in HTML code. $action is the URL to be submitted in the form, $name can specify the name of the form, and $target Specify whether to open a new window, etc.
The following addXXX series of methods are used to add corresponding controls to this form. The properties of the controls are also consistent with those in 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 the 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','login');
$myform->Display();
?>
7.Mail/RFC822
Checking whether an entered email is legal is not an easy task. You may try to use some regular expressions to check, but it is not so convenient and effective. Now, if you want to check whether a series of email addresses comply with the RFC822 standard and split them into separate email addresses, you can try this module, which is very simple and practical.
Usage: Mail_RFC822 ($address = null, $default_domain = null, $nest_groups = null, $validate = null)
class constructor, $address is a series of addresses you want to verify, $default_domain, specifies the default domain name or Hostname, $nest_groups Whether to group in the output so that $validate needs to validate each atom parseAddressList($address = null, $default_domain = null, $nest_groups = null, $validate = null) parse validation given The address list. If the address is valid, the split address list is returned. If an error occurs, an error message is returned.
<?php
require_once "Mail/RFC822.php";
$rf822 = new Mail_RFC822;
$result=$rf822->paseAddressList('who;[email protected];[email protected]');
if ( $rf822->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. This module allows you to use sendmail directly to send letters.
Usage: Mail_sendmail($params)
class constructor. $params is an associative array. You can set the parameters of sendmail. Currently Only 'sendmail_path' is valid, used to set the sendmail path send($recipients, $headers, $body) to send letters. $recipients is the email address of your recipient, which can be single or separated by; The open address list can be opened as long as it meets the RFC82 standard. $headers is the header of the letter you send. This is an associative number. The key of the array is the name of the header (such as Subject), and the array value is the value of the header (such as Hello!). The processed letterhead will be: Subject:Hello! $body is the body of the letter, including all 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'=>'[email protected]');
$body = 'This is a test message from nightsailer.com';
$result = $sendmail->send( '[email protected]' , $header, $body);
if ( PEAR::isError($result) ){
echo "<h1> Sending failed</h1><br>Reason: ".$result->getMessage()."<br>";
}else {
echo "<h1>Congratulations! Successfully sent!</h1><br>";
}
?>
9.Mail/smtp
Some sites currently do not allow the use of sendmail, so if your PHP program wants to use the mail sending function, it needs to be able to complete the corresponding function by using an external SMTP server.
Usage: Using this module is basically the same as Mail::sendmail. It should be noted that this module requires the use of Net::SMTP module: Mail_smtp($params)
Valid parameters for $params are:
'host' SMTP server address, the default is localhost
'port' smtp service port, the default is 25
'auth' Whether smtp requires authorization verification, the default is false
'usename' smtp authorized user name
'password' smtp authorized 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'=>'[email protected]');
$body = 'This is a test message from nightsailer.com';
$result = $sendmail->send( '[email protected]' , $header, $body);
if ( PEAR::isError($result) ){
echo "<h1> Sending failed</h1><br>Reason: ".$result->getMessage()."<br>";
}else {
echo "<h1>Congratulations! Successfully sent!</h1><br>";
}
?>
10.Schedule/At
This module provides the interface
add($cmd, $timespec, $queue = false, $mail = false)
of the at program on unix.
Appending 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 when the job starts execution, the format is the same as required by at
$queue optional parameter, indicating the queue name of the job
$mail optional parameter, indicating whether to send an email to report the running results after the job ends
show($queue = false)
The command displayed in the at queue returns an associative array. The key of the array is the job number. The corresponding key value is also an associative array. The content is array (runtime, queue). $queue is an optional parameter. You can use it. Limit to return only the job list in the queue whose queue name matches $queue
remove($job = false)
Delete the specified at job from the at queue. $job is the job number to be deleted. If successful, return true, otherwise return 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 add job!n";
echo "Reason: $result->getMessage() n";
exit;
}
//Display the current at queue
$queue = $at->show();
if ( PEAR::isError($queue) ) {
echo "An error occurred!n";
echo "Reason:" . queue->getMessage(). "n";
exit;
}
reset( $queue );
while ( list($job, $cmd) = each $queue ){
echo "[$job]" . $cmd['runtime'] . "-" .$cmd['queue'];
echo "n"
}
?>
The above are the uses of some PEAR modules. For more detailed instructions, you need to check the source files of these modules yourself, or you can use phpdoc to automatically generate the api documents of these modules. Regarding phpdoc, we will discuss it in detail in the next article.
4. Resources
PEAR CVS You can get the latest PEAR source code from here
Hoder project
PHPDoc Home Page