aeq/hal

此包最新版本(1.0.2)没有提供许可证信息。

1.0.2 2016-11-07 11:10 UTC

This package is auto-updated.

Last update: 2024-09-08 06:31:49 UTC


README

#PHP HAL (Hypertext Application Language) 探索器#

Build Status Code Coverage Scrutinizer Code Quality

此库提供了一个功能齐全的API,通过一个表达式的接口发现HAL(Hypertext Application Language)API。

$posts = $resource->getLink('posts')->follow();

特性

  • 默认使用GuzzleHttp作为HTTP客户端
  • 易于集成自定义HTTP客户端
  • 可读性强的API
  • 随附简单的默认序列化器,用于JSON响应
  • 可以集成自定义序列化器
  • 完全测试
  • 用于生产项目

##使用方法##

###1. 初始化探索器###

$explorer = new Explorer();
$explorer->setClientAdapter(new GuzzleClientAdapter(new Client()));
$explorer->setSerializer(new JsonSerializer());

如果您想使用内置的 "GuzzleClientAdapter",您必须在您的composer项目中手动require guzzlehttp/guzzle,因为guzzle只是建议使用的。

###2. 请求您的API###

$response = $explorer->request('GET', '/my/api/');

###3. 探索响应###

$resource = $explorer->explore($response);

###4. 发现您的API###

$posts = $resource->getLink('posts')->follow();
foreach($posts as $post) {
    $publisher = $post->getLink('publisher')->follow();
    $company = $publisher->getLink('company')->follow();
}

跟随链接的结果是将解析的资源附加到父 "$resource" 对象("_embedded")。这允许您访问链接资源而无需再次解析链接。

$posts = $resource->getEmbedded('posts');
foreach($posts as $post) {
    $publisher = $post->getEmbedded('publisher');
    $company = $publisher->getEmbedded('company');
}

##自定义HTTP客户端## 创建一个新的类实现 "ClientAdapterInterface",并将响应作为PSR-7返回。

use Aeq\Hal\Client\ClientAdapterInterface;

class MyCustomClientAdapter implements ClientAdapterInterface
{
    public function request($method, $uri = null, array $options = [])
    {
        // call your custom client and return the response
    }
}

在开始使用之前,将自定义客户端适配器设置到您的探索器中。

$explorer->setClientAdapter(new MyCustomClientAdapter());

##自定义序列化器## 创建一个新的类实现 "SerializerInterface",并返回响应。

use Aeq\Hal\Serializer\SerializerInterface;

class MyCustomSerializer implements SerializerInterface
{
    public function serialize($data)
    {
        // serialize your data: $data
    }

    public function deserialize($str)
    {
        // deserialize the string: $str
    }
}

在开始使用之前,将自定义序列化器设置到您的探索器中。

$explorer->setSerializer(new MyCustomSerializer());

##事件## 此库提供了一些您可以监听的事件。要使用事件系统,您必须在开始使用之前将 "EventManager" 添加到您的探索器中。

$explorer->setEventManager(new EventManager());

要监听特定事件,您必须实现一个监听器。监听器是一个具有公共方法 "handle" 的PHP对象。作为参数,您将获得触发的Event对象。

class MyHandler
{
    public function handle(EventInterface $event)
    {
        // process your stuff
    }
}

###PostClientRequestEvent### 在每次执行请求(在跟随链接或使用 "request" 方法后)时调用此事件,并包含完整的PSR-7响应。

$explorer->listenOnEvent(PostClientRequestEvent::class, new MyHandler());