switcher-io/switcher-php

switcher.io API 的 PHP 封装器

2.1 2020-04-28 21:33 UTC

This package is auto-updated.

Last update: 2024-08-29 05:43:14 UTC


README

Build Status

安装

使用 composer

$ composer require switcher-io/switcher-php

Dead Man Switch 示例

$urlId = 'url identifier of the switch, e.g. "abc123" in https://dmsr.io/abc123.';
$key = 'switch key';

//initialize the api
$sw = new \SwitcherIO\DeadManSwitch($urlId, $key);

//call the /start endpoint to signal your job started (optional - only used if your switch has a max run time set)
$sw->start();

//your job code goes here

//call /complete to notifiy Switcher.io the job has finished
$sw->complete();

//you can also pause the switch
$sw->pause();

错误处理

如果发生错误,或者 Switcher.io 没有响应表示调用成功,将会抛出 \SwitcherIO\SwitcherException。你可以使用 SwitcherExceptiongetStatusCode 方法来确定抛出异常的原因。状态码将与 \SwitcherIO\DeadManSwitch 的一个常量相匹配。

请务必使用错误处理!如果不这样做,调用 $sw->start() 可能会阻止你的工作完成。

use \SwitcherIO\DeadManSwitch;

$sw = new DeadManSwitch('url id', 'key');

try {
    $sw->start();
} catch (\SwitcherIO\SwitcherException $e) {

    if ($e->getStatusCode() === DeadManSwitch::STATUS_ERROR_404) {
        //oops, you either got the url id or key wrong...
    } else if ($e->getStatusCode() === DeadManSwitch::STATUS_ERROR_START_BEFORE_COMPLETE) {
        /*
         * You get this error if your switch is using a max runtime, and for some reason your job
         * starts a new run before the last run finished. If this is a problem for you, handle it here...
         */
    }

}

开发环境

你可能不希望你的本地开发环境向真实的开关发送ping。为了使库在本地或开发环境中进行模拟ping,请将url id设置为 'test' 或 'test-error'。

//in this case complete() act as if it ran succesfully, and will not actually ping a switcher.io url
$sw = new \SwitcherIO\DeadManSwitch('test', 'key-does-not-matter-for-test-url');
$sw->complete(); 

/*
 * In this case complete() will throw a \SwitcherIO\SwitcherException with a status code 
 * of \SwitcherIO\DeadManSwitch::STATUS_TEST_ERROR
 */
$sw = new \SwitcherIO\DeadManSwitch('test-error', 'key-does-not-matter-for-test-url');
$sw->complete();