dogado / json-api-client
JSON:API 协议的客户端侧 PHP 实现。
Requires
- php: ^8.0
- ext-json: *
- dogado/json-api-common: ^3.0
- psr/http-client: ^1.0
- psr/http-factory: ^1.0
Requires (Dev)
- fakerphp/faker: ^1.15
- http-interop/http-factory-guzzle: ^1.0
- phpstan/phpstan: ^0.12.91
- phpunit/phpunit: ^9.5
- squizlabs/php_codesniffer: ^3.6
Suggests
- guzzlehttp/guzzle: As a PSR-18 compatible HTTP client (version >=7.0).
- http-interop/http-factory-guzzle: For PSR-17 compatible factories.
This package is auto-updated.
Last update: 2024-09-17 15:34:02 UTC
README
安装
composer require dogado/json-api-client
建议安装 guzzlehttp/guzzle
版本 ^7.0
作为 http-client 和 http-interop/http-factory-guzzle
用于 PSR-17 兼容的工厂。
composer require guzzlehttp/guzzle http-interop/http-factory-guzzle
您也可以使用任何其他实现了 PSR-18 的 HTTP 客户端。
使用方法
首先,您应该阅读 dogado/json-api-common 的文档,其中将解释所有基本结构。
您的 API 客户端是 Dogado\JsonApi\Client\JsonApiClient
的一个实例,该实例需要一个 PSR-18 HTTP 客户端(Psr\Http\Client\ClientInterface
)来执行请求。
use Dogado\JsonApi\Client\JsonApiClient; use Dogado\JsonApi\Client\Factory\RequestFactory; use Dogado\JsonApi\Client\Validator\ResponseValidator; $client = new JsonApiClient( $httpClient, // instance of Psr\Http\Client\ClientInterface $psrRequestFactory, // instance of Psr\Http\Message\RequestFactoryInterface $streamFactory, // instance of Psr\Http\Message\StreamFactoryInterface $serializer, // instance of Dogado\JsonApi\Serializer\DocumentSerializerInterface $responseFactory, // instance of Dogado\JsonApi\Client\Response\ResponseFactoryInterface $authMiddleware // optional instance of Dogado\JsonApi\Client\Middleware\AuthenticationMiddlewareInterface. See docs below. ); $baseUrl = new Uri('http://example.com/api'); $requestFactory = new RequestFactory($baseUrl); $request = $requestFactory->createGetRequest(new Uri('/myResource/1')); // will fetch the resource at http://example.com/api/myResource/1 $response = $client->execute($request); // OPTIONAL: Validate the response to match your needs. See the ResponseValidator class for all assertion methods (new ResponseValidator())->assertResourcesMatchTypeAndContainIds($response, 'myResource'); $document = $response->document(); $myResource = $document->data()->first(); // the resource fetched by this request $myIncludedResources = $document->included()->all(); // the included resources fetched with the include parameter
行为模式
在大多数情况下,将请求场景封装到单个类中会更简单,因为每个请求都有自己的要求。在这个包中,这被称为 Action
。为了使事情更简单,我们已经在 Dogado\JsonApi\Client\Action
命名空间下定义了一个 AbstractAction
类。有关如何创建此类动作的示例,请参阅 测试。
在动作中获取资源时,也很常见要过滤、分页和排序。为了在动作中定义这些选项,可以使用多个 Traits,这些 Traits 定义在与 AbstractAction
类相同的命名空间中。
身份验证
当使用 JSON:API 客户端访问服务器应用程序时,您可能需要通过身份验证。由于这是一个常见用例,此客户端提供了称为“AuthenticationMiddleware”的内置身份验证支持,它由一个接口表示。客户端提供了一组内置的身份验证机制:OAuth2 客户端凭证和 HTTP 基本身份验证,但您可以根据需要基于 AuthenticationMiddlewareInterface
创建自定义中间件,或者可以自由创建一个 pull request 来添加更多身份验证。
use Dogado\JsonApi\Serializer\Deserializer; use Dogado\JsonApi\Serializer\Serializer; use Dogado\JsonApi\Client\JsonApiClient; use Dogado\JsonApi\Client\Response\ResponseFactory; use Dogado\JsonApi\Client\Middleware\AuthenticationMiddleware; /** @var Psr\Http\Client\ClientInterface $httpClient */ /** @var Psr\Http\Message\RequestFactoryInterface $requestFactory */ /** @var Psr\Http\Message\StreamFactoryInterface $streamFactory */ /** @var Psr\Http\Message\UriFactoryInterface $uriFactory */ // define which authentication you want to use (you can also leave the middleware `null` in order to use no authentication) $authenticationMiddleware = new AuthenticationMiddleware(); $client = new JsonApiClient( $httpClient, $requestFactory, $streamFactory, new Serializer(), new ResponseFactory( new Deserializer() ), $authenticationMiddleware ); ###### HTTP basic auth use Dogado\JsonApi\Client\Model\BasicCredentials; $authenticationMiddleware->setBasicCredentials(new BasicCredentials('username', 'password')); ###### OAuth 2 client credentials use Dogado\JsonApi\Client\Factory\Oauth2\CredentialFactory; use Dogado\JsonApi\Client\Service\OAuth2Authenticator; use Dogado\JsonApi\Client\Exception\Oauth2\AuthenticationException; # the Authenticator class also allows you to overload the HTTP client and the auth storage factory it uses $authenticator = new OAuth2Authenticator($httpClient, $requestFactory, $streamFactory, new CredentialFactory()); try { $oauth2Credentials = $authenticator->withClientCredentials($uriFactory->createUri('https://server.local/oauth/token'), 'Client-ID', 'Client-Secret'); $authenticationMiddleware->setOAuth2Credentials($oauth2Credentials); } catch (AuthenticationException $e) { // escalate any errors accordingly }
OAuth2
AuthenticationMiddleware
类需要一个包含访问令牌、令牌类型和过期日期的 Dogado\JsonApi\Client\Model\OAuth2Credentials
实例。您可以选择创建实例并插入所需数据,或者使用 Dogado\JsonApi\Client\Service\OAuth2Authenticator
类来生成它们。
请缓存 OAuth2Credentials
实例,只要方法 isExpired
不是 true
,以防止不必要的身份验证调用。
由于身份验证端点不遵循 JSON:API 协议,它也不会抛出特定的 JSON:API 错误或异常。唯一相关的错误是 Dogado\JsonApi\Client\Exception\Oauth2\AuthenticationException
类的变体,该类区分错误消息和代码。此类异常实例还包含作为 Psr\Http\Message\ResponseInterface
的纯响应,以便有更多的上下文来了解错误。
致谢
此包包含从 enm/json-api-client 中获取的代码。
许可
MIT 许可证 (MIT)。有关更多信息,请参阅 许可文件。