gsdevme/stubborn

该包最新版本(dev-master)没有可用的许可证信息。

概念来源于Stubborn https://github.com/derekdowling/stubborn

dev-master 2014-12-16 21:21 UTC

This package is auto-updated.

Last update: 2024-09-10 06:34:33 UTC


README

Travis

Build Status

Scrutinizer

Build Status Scrutinizer Code Quality Code Coverage

信用

我正在浏览Reddit,偶然看到了一篇帖子...我喜欢这个概念,但认为我可以改进实现方式,所以我就这么做了

概念

对于每个API供应商(例如Facebook,Twitter,Dropbox),让请求实现StubbornAwareInterface并将类扔入Stubborn,你可以实现方法来处理API的怪异之处

示例

class StubbornDummyApi implements \Stubborn\StubbornAwareInterface
{

    private $apiKey;

    public function __construct($apikey)
    {
        $this->apiKey = $apiKey;
    }

    public function getRetryNumber()
    {
        // try twice
        return 1;
    }

    public function getRetryWaitSeconds()
    {
        // wait 5 seconds after each try
        return 10;
    }

    public function run()
    {
        // use the API key or something in the real world?
        $this->apiKey = null;

        // Actual API logic here.. so Facebook, Twitter etc
        return new \Stubborn\StubbornResponse('{"status":true}', 200);
    }

    public function getHttpActionRequest(\Stubborn\StubbornResponseInterface $response)
    {
        // Handle the HTTP code, 501/408 lets retry
        switch($response->getHttpCode()){
            case 501:
            case 408:
                return self::RETRY_ACTION;
            default:
                return false;
        }
    }

    public function getExceptionActionRequest(\Exception $exception)
    {
        switch(true){
            // If UnexpectedValueException retry wait.. maybe got something odd back from the API
            case ($exception instanceof \UnexpectedValueException):
                return self::RETRY_WAIT_ACTION;
            // Default action is to just rethrow the Exception, we don't know what to do with it
            case ($exception instanceof \Exception):
            default:
                throw $exception;
        }
    }
}

$dummyApiRequest = new StubbornDummyApi('123456789qwerty');
$stubborn = new \Stubborn\Stubborn($dummyApiRequest);
$result = $stubborn->run();

if($result instanceOf \Stubborn\StubbornResponseInterface){
    var_dump($result->getHttpCode());
    var_dump($result->getData());
}