wonnova/woost-gamification-php-sdk

Woost SDK for PHP。直接从您的PHP项目中使用Woost的RESTful API

v0.2.1 2016-04-12 19:48 UTC

This package is not auto-updated.

Last update: 2024-09-24 04:09:58 UTC


README

Woost SDK for PHP。直接从您的PHP项目中使用 Woost 的RESTful API

Build Status Code Coverage Scrutinizer Code Quality Latest Stable Version License

安装

首选的安装方法是 composer。只需在您的项目中运行此命令即可更新您的 composer.json 文件并安装依赖项。

composer require wonnova/woost-gamification-php-sdk

如果您从未使用过composer,请查看其 文档

使用方法

此库基本上提供了一个简单的 Client 对象,用于对RESTful API进行请求。

include __DIR__ . '/../vendor/autoload.php';

// Create the client and inject a Credentials instance on it with your private key
$wonnovaClient = new \Wonnova\SDK\Connection\Client(
    new \Wonnova\SDK\Auth\Credentials(['key' => 'AaBbCcDd123456'])
);

// After this point, you are able to perform requests to the API
try {
    // Create a new user in your system
    $user = new \Wonnova\SDK\Model\User();
    $user->setUsername('john.doe')
         ->setProvider('my_company_name')
         ->setFullName('John Doe')
         ->setDateOfBirth(new \DateTime('1980-03-09 18:56:00'))
         ->setEmail('jdoe@doamin.com');
    $wonnovaClient->createUser($user);
    
    // Once the user is created, the userId is populated if it wasn't previously set.
    echo $user->getUserId();
    
    // Make the user perform an action
    // The userId can be used if you don't have access to the full User object
    $actionCode = 'LOGIN';
    $wonnovaClient->notifyAction($user, $actionCode);
    
    // You can now get the list of your quests and the status of the user in each one of them
    $quests = $wonnovaClient->getUserStatusInQuests($user);
    // This method returns an iterable collection of Quest instances, each one of them with the list of QuestSteps
    foreach ($quests as $quest) {
        echo sprintf('Quest code: %s', $quest->getCode());
        echo sprintf(
            'Quest start date: %s',
            $quest->getStartDate()->format('Y-m-d H:i:s')
        );
        
        // Get the quest steps
        foreach ($quest->getQuestSteps() as $step) {
            echo sprintf('Quest %s. Step type: %s', $quest->getName(), $step->getType());
            echo sprintf('Quest %s. Step code: %s', $quest->getName(), $step->getCode());
            echo sprintf(
                'Did "%s" complete this step? %s',
                $user->getFullName(),
                ($step->isCompleted() ? 'YES' : 'NO')
            );
        }
    }
} catch (\Wonnova\SDK\Exception\ExceptionInterface $e) {
    echo $e->getTraceAsString();
}

Client对象获取两个额外的参数。第一个是您希望获取响应的语言,默认为es

第二个是一个缓存适配器(Doctrine\Common\Cache\Cache 的实例)。默认情况下,使用指向系统临时目录的FilesystemCache实例。

此适配器用于在请求之间存储认证令牌以提高性能。如果您可以访问像Redis、Memcached或OPcache这样的“更快”的东西,我们建议您使用另一个缓存适配器。

$memcached = new \Memcached();
$memcached->addServer('127.0.0.1', 11211)
$cacheAdapter = new \Doctrine\Common\Cache\MemecachedCache();
$cacheAdapter->setMemcached($memcached);

$wonnovaClient = new \Wonnova\SDK\Connection\Client(
    new \Wonnova\SDK\Auth\Credentials(['key' => 'AaBbCcDd123456']),
    'es',
    $cacheAdapter
);

错误管理

Client对象中的每个方法至少将执行一个HTTP请求(如果需要执行重新认证,则可能更多)。如果服务器返回状态码为200的响应,则将解析响应内容,但4xx和5xx状态码可能会抛出异常。

  • 401:当认证令牌无效时可能会返回。在这种情况下,客户端将自动重新认证。如果服务器返回此状态码但不是INVALID_TOKEN响应,则将抛出 Wonnova\SDK\Exception\UnauthorizedException
  • 400:当由于某些原因执行了无效请求时,例如无效参数等,将返回此状态。这种情况将抛出 Wonnova\SDK\Exception\InvalidRequestException
  • 404:如果由于某种原因请求的URL不存在并返回404错误,则将抛出 Wonnova\SDK\Exception\NotFoundException。在正常情况下,这不应该发生,除非您手动对自定义路由执行请求。
  • 500:当然,如果发生服务器错误,将抛出 Wonnova\SDK\Exception\ServerException
  • 其他:不应返回其他状态码,但如果发生错误,则将抛出 Wonnova\SDK\Exception\RuntimeException

所有4xx异常都扩展自公共 Wonnova\SDK\Exception\ClientException,并且此包中的所有异常都实现了公共 Wonnova\SDK\Exception\ExceptionInterface 以便于捕获它们。

未来兼容性

如果由于某种原因,在发布此SDK的新版本之前,Wonnova必须发布带有新端点的新API版本,并且您需要消费这些新端点,有方法可以实现。

使用公共 connect 方法,您将获得任何路由请求的原始响应。您不会得到映射对象,但您将能够手动解析响应并与之交互。

$method = 'GET';
$route = '/foo/bar/' . $userId;

// This response object is a GuzzleHttp\Message\ResponseInterface instance
$response = $wonnovaClient->connect($method, $route);
$data = json_decode($response->getBody()->getContents(), true);

// To send information in the body, like in POST and PUT requests, use the third argument like this
$response = $wonnovaClient->connect('POST', '/resource/create', [
    'json' => [
        'resourceId' => '123',
        'foo' => 'bar'
    ]
]);

依赖注入和测试

如果您需要依赖于Wonnova的Client对象,始终使用 Wonnova\SDK\Connection\ClientInterface 而不是具体的 Client 对象。这样,在需要的情况下,您将能够替换该对象。

如果您不想替换Client对象中的所有方法,但需要测试依赖于它的另一个对象,并且不想执行真实的HTTP请求,那就没有问题。对象Wonnova\SDK\Connection\Client基于并扩展了GuzzleHttp\Client,因此您将能够按照说明这里进行HTTP请求的模拟。

示例。

// Create a client instance
$wonnovaClient = new \Wonnova\SDK\Connection\Client(
    new \Wonnova\SDK\Auth\Credentials(['key' => 'AaBbCcDd123456'])
);

// Create a mock subscriber
$mockSubscriber = new \GuzzleHttp\Subscriber\Mock([
    // Add a response that will mock the authentication request
    new \GuzzleHttp\Message\Response(
        200,
        [],
        new \GuzzleHttp\Stream\Stream(fopen('data://text/plain,{"token": "foobar"}', 'r'))
    ),
    
    // Add another response that will mock the request you want to test
    new \GuzzleHttp\Message\Response(
        200,
        [],
        new \GuzzleHttp\Stream\Stream(fopen('data://text/plain,...', 'r'))
    ),
]);

// Set the mock subscriber to the client instance
$wonnovaClient->getEmitter()->attach($mockSubscriber);
$wonnovaClient->getUsers(); // This won't perform a real HTTP request

您只需设置一个与SDK期望从请求中获取的内容兼容的响应内容。

文档

如果您需要了解此SDK所消费的API的规范,或者想要获取SDK本身的扩展文档,请随时联系我们