PHPのMechanizeの例外処理

そもそもPHPにMechanizeはないけど!!

RubyのWWW::Mechanizeの例外処理
http://june29.jp/2007/12/02/ruby-mechanize-rescue-exception/

↑のサンプルが簡略かされてるんで処理がよく見えないけど、
URLのリストがあって、それにバンバンアクセスするって場合、
PHPだとこんな感じなのかなあ。

<?php
require_once 'Zend/Loader.php';
Zend_Loader::registerAutoload();

class My_Http_Mechanize extends Zend_Service_Abstract
{
    protected static $_httpClient = null;
    
    public $urls;

    public function get($url, $method = Zend_Http_Client::GET)
    {
        $client = self::getHttpClient();
        if ($url) $client->setUri($url);
                
        $response = $client->request($method);
        
        if (!$response->isSuccessful()) {
            throw new ResponseCodeException('ResponseCodeException', response->getStatus());
        }
        
        return $response->getBody();
    }
    
}
class ResponseCodeException extends Exception
{}
//////////////////////////////////////////////////////////////
$mecha = new My_Http_Mechanize();

$urlarray = array('http://test.org/', 'http://test2.org/', 'http://test3.org/');
$urls = new ArrayIterator($urlarray);

do {
    try {
        $page = $mecha->get($urls->current());
        
        echo 'get success!! ->'; echo $urls->current();
        echo PHP_EOL;
        
        $urls->next();
    } catch (Zend_Http_Client_Adapter_Exception $e) {
        if ($e->getMessage() == 'Unable to set the connection timeout') { 
      //Message文字列で判断してるのがダサい。
            echo $e->getMessage(); 
            //sleep();
        }
    } catch (ResponseCodeException $e) {
        switch ($e->getCode()) {
            case 404 :
                echo Zend_Http_Response::responseCodeAsText($e->getCode());
                echo '-> '. $urls->current();
                
                $urls->next(); #ページが見付からないときは次へ
            break;
            case 502 :
                echo Zend_Http_Response::responseCodeAsText($e->getCode());
                echo '-> '. $urls->current();
            break;
        }
        echo PHP_EOL;       
    }
} while ($urls->valid());

Rubyのretryの替わりってわけじゃないけど、responseがサクセスフルと404以外のときはイテレータ進ませないとかしてdo whileしまくる!おそろしい!まあ、404じゃなくても何回かリクエストしてサクセスしなかったらそれ相応の処理ですね。



上のを適当にステータスかまして実行した場合の結果(サンプル)

get success!! ->http://test.org/
Bad Gateway-> http://test2.org/
Bad Gateway-> http://test2.org/
Bad Gateway-> http://test2.org/
get success!! ->http://test2.org/
Bad Gateway-> http://test3.org/
Not Found-> http://test3.org/

以上、「Rubyってretryってのがあるんだ。へぇ良いなあ」ていうエントリでした。
(PHPでも別にスマートな書き方がある気がする)