artesaos/restinga

Restinga 是一个框架,允许您轻松消费 Rest API

1.1.0 2017-09-24 02:11 UTC

This package is auto-updated.

Last update: 2024-08-25 04:22:33 UTC


README

Restinga 是一个 ActiveResource 框架。这是什么意思?它允许您以简单直观的方式消费 Rest API。灵感主要来源于 Laravel 的 Eloquent(ActiveRecord 库)。

Latest Stable Version Total Downloads Latest Unstable Version License Monthly Downloads

文档

深入了解文档

为什么要构建它?

嗯,有时候公司提供的 PHP 客户端真的很糟糕,你知道的。有时候它们甚至比直接使用 CURL API 更难用。我们已经构建了这个包来帮助你在这种情况发生时。

快速入门指南

在我们的快速使用教程中,让我们以 Digital Ocean 作为我们要消费的示例 Rest API。

1 - 定义 API 服务。
<?php namespace Artesaos\DigitalOcean;

use Artesaos\Restinga\Authorization\Bearer;
use Artesaos\Restinga\Service\Descriptor;

class DigitalOceanDescriptor extends Descriptor
{
    // service alias
    protected $service = 'digital-ocean';

    // api prefix
    protected $prefix = 'https://api.digitalocean.com/v2';

    // how to authenticate on the api
    public function authorization()
    {
        return new Bearer('your-token-here');
    }
}
2 - 在 Restinga 容器中注册 API
use Artesaos\DigitalOcean\DigitalOceanDescriptor;
use Artesaos\Restinga\Container;

Container::register(new DigitalOceanDescriptor());
3 - 定义 API 资源
<?php namespace Artesaos\DigitalOcean\Resource;

use Artesaos\Restinga\Data\Resource;
use Artesaos\Restinga\Http\Format\Receive\ReceiveJson;
use Artesaos\Restinga\Http\Format\Receive\ReceiveJsonErrors;
use Artesaos\Restinga\Http\Format\Send\SendJson;

class Droplet extends Resource
{
    // send & receive formats
    use ReceiveJson;
    use SendJson;

    // errors format
    use ReceiveJsonErrors;

    // the service to use (defined on the descriptor)
    protected $service = 'digital-ocean';

    // api resource to consume
    protected $name = 'droplets';

    // resource identifier
    protected $identifier = 'id';

    // resource collection root
    protected $collection_root = 'droplets';

    // resource single item root
    protected $item_root = 'droplet';
}
4 - 使用它!
<?php

use Artesaos\DigitalOcean\Resource\Droplet;

$droplet = new Droplet();
$droplet->name = 'server.restinga.dev';
$droplet->region = 'nyc3';
$droplet->size = '512mb';
$droplet->image = 'ubuntu-14-04-x64';

$saved = $droplet->save();

if ($saved) {
    echo $droplet->id; // 4242424
} else {
    foreach ($droplet->errors->all() as $code => $error) {
        echo $code . ": " . $error . "\n";
    }
}