remluben/cockpit-client

cockpit无头CMS的一个简单只读API客户端

v1.1.0 2022-09-23 19:29 UTC

This package is auto-updated.

Last update: 2024-09-23 23:41:07 UTC


README

注意

此库可以与新的Cockpit - 内容平台一起使用,这是Cockpit无头API-first CMS的一个全新版本。

对于这个基本版本,API客户端是只读的。这可能在未来的版本中会改变。

一个用于访问cockpit无头CMS数据的非常简单直接的只读API的PHP客户端。

安装

您可以通过composer安装此包

composer require remluben/cockpit-client

这就完了。第一步不需要更多步骤。

用法

本节提供用法信息。我们将\Remluben\CockpitClient\Client类的实例称为客户端

基础知识

首先确保以合理的Guzzle设置配置您的客户端,以避免超时和性能不佳。然后您可以通过调用客户端提供的任何方法来从您的Cockpit安装中获取数据。

// Set up your basic HTTP client, which makes the HTTP requests to Cockpit under
// the hood.
$http = new GuzzleHttp\Client([
    GuzzleHttp\RequestOptions::TIMEOUT => 2.0, // set an appropriate timeout that suits your application and server needs
    GuzzleHttp\RequestOptions::DEBUG => false, // optionally enable in development mode
]);

// Create an instance of the Cockpit client by passing all required data
$client = new Remluben\CockpitClient\Client(
    $http,                                          // The HTTP client
    'https://url-to-cockpit.tld/api/',              // The URL to the API of your Cockpit instance, i.e. https://url-to-cockpit.tld/api/
    'API-1a45a0876a88fb3f042cc6524059a4a11bf3f163', // a static token / api-key for server-side usage, should not expire
);

$results = [];
// Fetch your first content items, i.e. for content model *faqs*
try {
  $results = $client->contentItems('faqs');
}
catch (\Remluben\CockpitClient\Exceptions\ClientException $e) {
  // A client exception happens whenever 
  // - the HTTP client itself rises an exception
  // - the Cockpit API returns non 2xx status codes or runs into issues
}
catch (\Remluben\CockpitClient\Exceptions\InvalidArgumentException $e) {
  // For unintended method calls, invalid parameters or similar problems the
  // client usually throws this exception 
}

// process your results, if any...
foreach ($results as $item) {
  // do something here...
}

错误处理

错误处理应该是相当直接的。每当发生意外情况,当API响应返回不良的HTTP状态码或错误时,客户端会抛出异常。

换句话说,这意味着:只有当HTTP状态码为200并且有有效的JSON响应时,请求才被视为成功。

变更日志

有关最近更改的更多信息,请参阅变更日志

许可证

本软件根据MIT许可证发布。