linkorb/primate

Primate:RESTful API 库

dev-master 2016-04-30 10:20 UTC

This package is auto-updated.

Last update: 2024-08-29 04:14:36 UTC


README

Primate是一个帮助创建美观REST API的库。

它深受Stormpath的《REST API设计基础》的启发

使用Primate

首先需要实例化Primate,然后应用程序才能处理请求

use Primate\Primate;

$primate = new Primate();
$primate->setBaseUrl('http://primate.example.com/api/v1');
$primate->setProperty('tenant', 'joe');
$primate->setProperty('x', 'y');

您会注意到API的BaseUrl已经设置在Primate实例中,以便输出正确的URL。

此外,我们还注册了一些任意的属性来定义请求的上下文。您可以在以后使用这些属性来获取资源。

资源和集合

在Primate API中,客户端可以操作资源和集合。

  • 资源仅仅是应用程序中的一个“对象”。例如,用户、产品等。
  • 集合是资源的一个数组。

类型

每个资源都是特定类型的。

在Primate中,您需要在使用之前注册一个或多个类型。例如

$repo = new MyContactRepository();
$type = new Type('contacts', $repo);
$primate->registerType($type);

每个类型都有一个名称和一个存储库。存储库可以是任何实现Primate\RepositoryInterface的类。

建议使用现有的应用程序存储库,并使其实现此接口。

例如

<?php

namespace Example;

use Primate\RepositoryInterface;
use Primate\Resource;
use Primate\Primate;
use RuntimeException;

class PdoContactRepository implements RepositoryInterface
{
    public function __construct($pdo)
    {
        $this->pdo = $pdo;
    }
    
    // Implement your regular repository methods here...
    
    public function loadResourceCollection(Collection $collection, Primate $primate)
    {
        foreach ($this->getAllContacts() as $contact) {
            $resource = new Resource($collection->getType(), $contact->getId());
            $collection->addResource($resource);
        }
    }
    
    public function loadResources($resources, Primate $primate)
    {
        foreach ($resources as $resource) {
            $contact = $this->findById($resource->getId());
            $resource->setProperty('name', $contact->getName());
            $resource->setProperty('gender', $contact->getGender());
            $phoneResource = $primate->createResource('phones', $contact->getPhoneId());
            $resource->setProperty('phone', $phoneResource);
        }
    }
}

Primate将调用这些方法来加载数据。

调用Primate

您可以通过以下方式向Primate发出请求

$data = $primate->getDataByPath($path, $expands);
echo json_encode($data, JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES);

path变量可以是

  • /{typeName}:这将返回该类型所有资源的集合
  • /{typeName}/{resourceId}:这将返回特定的资源

此外,您可以传递一个expands数组。

子资源扩展

当在expands参数中传递键时,Primate将自动扩展指定的子资源。

例如,如果您的第一个响应如下所示

{
    "href": "http://primate.example.com/api/v1/contacts/1",
    "name": "Alice",
    "gender": "Female",
    "phone": {
        "href": "http://primate.example.com/api/v1/phones/xyz"
    }
}

您可以让Primate“扩展phone属性

{
    "href": "http://primate.example.com/api/v1/contacts/1",
    "name": "Alice",
    "gender": "Female",
    "phone": {
        "href": "http://primate.example.com/api/v1/phones/xyz",
        "number": "+1 987654321",
        "type": "mobile"
    }
}

许可证

MIT(见LICENSE.md

由LinkORB工程团队提供


请查看我们的其他项目linkorb.com/engineering

顺便说一句,我们在招聘!