Write less php codes with PEAR

August 12, 2010 | In: pear, PHP

In web development, it’s a good practice to always write classes that can be ‘reuse’ in your succeeding projects. Good thing there is pear, collection of php classes that is developed by community and of guess what, it’s open source =).

A default php has a few pear libraries installed. To add what you need, follow this simple command:

$ sudo pear install [package_name]

Where [package_name] is the library you want to install.

For example we want to have a ‘Mail’ pear library,

$ sudo pear install Mail Mail_Mime

You will see something like this:

Starting to download Mail-1.2.0.tgz (23,214 bytes)
........done: 23,214 bytes
downloading Mail_Mime-1.8.0.tgz ...
Starting to download Mail_Mime-1.8.0.tgz (31,292 bytes)
...done: 31,292 bytes
install ok: channel://pear.php.net/Mail-1.2.0
install ok: channel://pear.php.net/Mail_Mime-1.8.0

We can verify if those two packages are installed by invoking this command:

$ pear list
Installed packages, channel pear.php.net:
=========================================
Package             Version State
Archive_Tar         1.3.2   stable
Console_CommandLine 1.1.0   stable
Console_Getopt      1.2.3   stable
File                1.3.0   stable
File_Find           1.3.0   stable
Mail                1.2.0   stable
Mail_Mime           1.8.0   stable
PEAR                1.6.1   stable
Structures_Graph    1.0.2   stable

These are my pear libraries installed on my system, it may not be the same from yours.

Now, lets proceed to the code:

 'you@yourdomain.com',
              'Subject' => 'Test mime message'
              );
$mime = new Mail_mime($crlf);

$mime->setTXTBody($text);
$mime->setHTMLBody($html);
$mime->addAttachment($file, 'text/plain');

//do not ever try to call these lines in reverse order
$body = $mime->get();
$hdrs = $mime->headers($hdrs);

$mail =& Mail::factory('mail');
$mail->send('postmaster@localhost', $hdrs, $body);

(the code is directly copied from this pear mail example)

Only your imagination is the limit on what you can achieve using pear.

Comment Form