PHPを便利にする10個のPEARライブラリ

PHPを便利にする10個のPEARライブラリの紹介です。
PHPには開発を便利にするPEARライブラリがあり、長くなりがちなコードをシンプルにすることができます。
これからPHPを始めてみようかなぁって方にはとくに魅力を感じるものだと思います。
#インストールや管理がコマンドラインで簡単にできるのも特徴。

Calendar


カレンダーの作成が簡単にできる。曜日の取得はもちろんのこと、祝日の取得や前の月・次の月の取得が行える。
インストール方法

pear install Calendar-0.5.4

サンプルコード

<?php
require_once 'Calendar/Month/Weekdays.php';
$calMonth = new Calendar_Month_Weekdays(2006, 8, 0);
$calMonth->build();
echo <<<EOD
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body>
<table><thead><tr>
<th>月</th><th>火</th><th>水</th><th>木</th><th>金</th><th>土</th>
</th><th>日</th>
</tr></thead><tbody>
EOD;
while ($day = $calMonth->fetch()) {
    if ($day->isFirst()) {
        echo '<tr>';
    }
    if ($day->isEmpty()) {
        echo '<td>&nbsp;</td>';
    } else {
        echo '<td>'.$day->thisDay().'</td>';
    }
    if ($day->isLast()) {
        echo '</tr>';
    }
}
echo <<<EOD
</tbody></table>
</body>
</html>
EOD;
?>

Image_Transform


画像のリサイズが簡単にできる。
インストール方法

pear install Image_Transform-0.9.3

サンプルコード

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body>
<?php
require_once("Image/Transform.php");
$input_file  = "sample.jpg";
$output_file = "sample_out.jpg";
$imgObj =& Image_Transform::factory('GD');
$imgObj->load( $input_file );
$imgObj->scaleMaxLength( 240 );
$imgObj->setOption( 'quality', 80 );
$result = $imgObj->save( $output_file, 'jpg' );
?>
<h2>オリジナル</h2>
<img src="sample.jpg">
<h2>縮小表示</h2>
<img src="sample_out.jpg">
</body>
</html>

XML/Serializer


XMLデーターを配列に変換してくれる。
インストール方法

pear install XML_Serializer-0.20.0

サンプルコード

<?php
require_once 'XML/Unserializer.php';
$xml = file_get_contents( "http://moeten.info/maidcafe/?m=api&type=shop" );
$Unserializer =& new XML_Unserializer(
    array('parseAttributes' => true,
    'targetEncoding'  => 'utf-8'
    )
);
$status = $Unserializer->unserialize($xml);
if (PEAR::isError($status)) {
    die($status->getMessage());
}
$xml = $Unserializer->getUnserializedData();
var_dump( $xml );
?>

Net_UserAgent_Mobile


携帯端末の情報を簡単に取得できる。解像度の情報も取得できる。
インストール方法

pear install Net_UserAgent_Mobile-1.0.0

サンプルコード

<?php
require_once 'Net/UserAgent/Mobile.php';
$agent = &Net_UserAgent_Mobile::factory();
if( $agent->isDoCoMo() ) {
    echo "docomoの携帯をご利用ですね";
}
$display = $agent->getDisplay();
var_dump( $display );
?>

MDB2


多様なデーターベースに接続できる。PostgressからMySQLに以降する場合も簡単に切り替えることが可能。
インストール方法

pear install MDB2-2.5.0b2

サンプルコード

<?php
require_once 'MDB2.php';
$dsn = array(
    'phptype'  => 'mysql',
    'username' => 'root',
    'password' => '',
    'hostspec' => 'localhost',
    'database' => 'test',
);
$mdb2 =& MDB2::connect($dsn);
$res =& $mdb2->query('SELECT * FROM mdb2test ');
while (($row = $res->fetchRow())) {
    var_dump( $row );
}
?>

開発者向け?

Service_Xxxx


Youtube,Amazon,などのWebサービスPHPから簡単に呼び出して情報を取得することができる。
簡単に調べたところ以下のものがあります。
Services_Amazon_SQS
Services_Ebay
Services_Facebook
Services_Google
Services_Hatena
Services_TinyURL
Services_Twitter
Services_Weather
Services_Yahoo_JP
Services_YouTube
今回はサンプルとしてはてなの情報が取得できる Services_Hatena を使ってみました。
インストール方法

pear install Services_Hatena-0.1.4

サンプルコード

<?php
require_once 'Services/Hatena.php';
$url = "http://www.google.co.jp/";
$hatena = & Services_Hatena::factory('Bookmarknum');
$nums = $hatena->execute($url);
echo <<<EOD
<h1>{$url}の被ブックマーク数@はてな</h1>
EOD;
var_dump($nums);
?>

Main/Mime


メールサーバーに接続したりファイル付きのメールを送ることができる。HTML形式のメールも可。
インストール方法

pear install Mail_Mime-1.5.2

サンプルコード

<?php
include('Mail.php');
include('Mail/mime.php');
$text = 'Text version of email';
$html = '<html><body>HTML version of email</body></html>';
$file = 'sample.jpg';
$crlf = "\n";
$hdrs = array(
              'From'    => '送信元メールアドレス',
              'Subject' => 'Test mime message'
              );
$mime = new Mail_mime($crlf);
$mime->setTXTBody($text);
$mime->setHTMLBody($html);
$mime->addAttachment($file, 'text/plain');
$body = $mime->get();
$hdrs = $mime->headers($hdrs);
$mail =& Mail::factory('mail');
echo $mail->send('送信先メールアドレス' , $hdrs, $body);
echo "sended";
?>

HTTP_Client


あたかもブラウザからアクセスしている振る舞いができる。ニコニコ動画へログインして情報を取得することが可能。
インストール方法

pear install HTTP_Client-1.2.1

サンプルコード

<?php
//ニコニコへログイン
$mail = "メールアドレス";
$pwd  = "パスワード";
require_once 'HTTP/Client.php';
$client = new HTTP_Client();
$client->setDefaultHeader('Keep-Alive', 4);
$conf = array('mail' => $mail, 'password' => $pwd);
$client->post('https://secure.nicovideo.jp/secure/login?site=niconico', $conf);
$res = $client->currentResponse();
print_r( $res );
exit;
?>

Cache_Lite


簡単に出力するHTMLページのキャッシュを作成することができる。キャッシュ有効期間の設定が可能なのが便利。
インストール方法

pear install Cache_Lite-1.7.8

サンプルコード

<?php
require_once "Cache/Lite.php";
$options = array(
    'cacheDir' => '/tmp/',
    'lifeTime' => 7200
);
$cache = new Cache_Lite($options);
if ($data = $cache->get('id_of_the_page')) {
    echo <<<EOD
キャッシュが見つかりました。
キャッシュから表示します。
EOD;
    echo $data;
} else {
    $data = '<html><head><title>test</title></head><body><h2>Cache Test.</h2></body></html>';
    echo $data;
    $cache->save($data);
}
?>

BentchMark


プログラムの特的の箇所のベンチマークを取ることができる。
インストール方法

pear install Benchmark-1.2.7

サンプルコード

<?php
require_once 'Benchmark/Timer.php';
$timer = new Benchmark_Timer();
$timer->start();
$timer->setMarker('Marker 1');
sleep(3);
$timer->setMarker('Marker 2');
$timer->stop();
$timer->display();
$profiling = $timer->getProfiling();
?>

他にも便利なPEARライブラリがありましたら教えてほしいです(^−^)
#PEARを調べてたら、いろいろと楽しいライブラリが出てきたのでも一回復習したいところ。RSSで配信してないのかなぁ。
補足説明
PEAR本体が古くてライブラリのインストールできない場合
php/PEARgo-pearを最新のものにする
以下のコマンドを実行していく。

pear update-all

次回はPHPフレームワークかなぁ。まだ勉強してないので、なんともかんともですが汗