enm / json-api-server-resource-mappers
Requires
- php: >=7.0
- enm/json-api-server: ^2.0
Requires (Dev)
- phpunit/phpunit: ^6.3
This package is auto-updated.
Last update: 2022-02-01 13:09:37 UTC
README
这个抽象库是enm/json-api-server的扩展,它添加了一个实现来标准化JSON API资源与实体之间的映射。
动机
这个库的动机是经常需要映射实体(例如使用doctrine或elasticsearch)和由enm/json-api-server提供的JSON API资源之间的属性。
已经证明,不同项目之间的映射器和关联注册的结构实际上并没有变化。
安装
composer require enm/json-api-server-resource-mappers
使用
资源映射器旨在在您的资源处理器或提供者中使用,以解耦资源和实体与处理器。
您应该始终使用提供对所有映射器访问权限的注册表,而无需您的实现了解实体如何以及在哪里映射到资源,以及如何返回。
$resourceMapper = new ResourceMapperRegistry(); // add your resource mappers to the registry $resourceMapper->addMapper(new \CustomMapper());
在您的请求处理器方法 fetchResource
// fetch entity into $entity if($resourceMapper instanceof JsonApiAwareInterface){ $resourceMapper->setJsonApi($this->jsonApi()); } $resource = $this->jsonApi()->resource('examples','1'); $resourceMapper->toResource($entity, $request, $resource); // return your document containing the resource
资源映射器
您的资源映射器必须实现 Enm\JsonApi\Server\ResourceMappers\Mapper\ResourceMapperInterface
方法 | 返回类型 | 描述 |
---|---|---|
supportsEntity(EntityInterface $entity) | bool | 指示此映射器是否可以处理给定的实体 |
toResource(EntityInterface $entity, FetchRequestInterface $request, ResourceInterface $resource) | void | 将给定的实体映射到给定的(空)API资源 |
toEntityFull(ResourceInterface $resource, EntityInterface $entity) | void | 将给定的API资源的所有字段从POST请求映射到给定的实体,如果缺少必需的元素则抛出异常 |
toEntityPartial(ResourceInterface $resource, EntityInterface $entity) | void | 将给定的API资源的可用字段从PATCH请求映射到给定的实体 |
为了简化使用,您的映射器可以扩展 Enm\JsonApi\Server\ResourceMappers\Mapper\AbstractResourceMapper
,它已经实现了 Enm\JsonApi\JsonApiAwareInterface
和 Enm\JsonApi\Server\ResourceMappers\Mapper\ResourceMapperAwareInterface
。
抽象映射器还实现了 toResource
方法,但要求您的映射器实现 mapAttributesToResource
、mapMetaInformationToResource
和 mapRelationshipsToResource
。
如果您的映射器不需要这些方法中的一种,这些特质包含默认(空)实现,并且可以用来使用。
Enm\JsonApi\Server\ResourceMappers\Mapper\NoAttributesTrait
Enm\JsonApi\Server\ResourceMappers\Mapper\NoMetaInformationTrait
Enm\JsonApi\Server\ResourceMappers\Mapper\NoRelationshipsTrait
资源映射器感知
如果您想使用嵌套资源映射(例如使用JSON API关系和includes),您的映射器可以实现 Enm\JsonApi\Server\ResourceMappers\Mapper\ResourceMapperAwareInterface
并使用 Enm\JsonApi\Server\ResourceMappers\Mapper\ResourceMapperAwareTrait
,它提供了 resourceMapper
方法来访问资源映射器注册表。
Json Api Aware
如果您想使用json api(例如用于关系),您的映射器可以实现Enm\JsonApi\JsonApiAwareInterface
并使用Enm\JsonApi\JsonApiAwareTrait
,该trait提供了jsonApi
方法来访问json api。作为替代,您也可以扩展实现了json api aware的抽象映射器。
如果您的映射器之一使用了json api aware,则需要在请求处理器中将其设置为映射器(注册表),然后请求处理器也必须实现Enm\JsonApi\JsonApiAwareInterface
。