我们目前正在开发一个 API laminas/mezzio
,我想为details
和list
路由生成不同的输出。我正在寻找一种生成以下结果的方法:
列表响应
{
"_total_items": 2,
"_page": 1,
"_page_count": 1,
"_links": {
"self": {
"href": "https://api.domain.tld/snapshot?page=1"
}
},
"_embedded": {
"snapshot": [
{
"id": "9c81ed3e-4ec4-4c5f-a3a1-d14e499b2607",
"name": "Lorem Ipsum 1"
},
{
"id": "6381ed3e-4ec4-4c5f-a3a1-d14e499b2633",
"name": "Lorem Ipsum 2"
}
]
}
}
细节反应
{
"id": "9c81ed3e-4ec4-4c5f-a3a1-d14e499b2607",
"name": "Lorem Ipsum 1",
"foo": "bar",
"more": "fields"
}
为此,我找到了 package jms/serializer
。我已经添加了序列化程序所需的所有注释并且它可以工作。但是我有点迷失如何将这个包laminas/mezzio
与学说2和laminas/mezzio-hal
我的列表处理程序:
<?php
class ListHandler implements RequestHandlerInterface
{
protected SnapshotServiceInterface $snapshotService;
protected HalResponseFactory $halResponseFactory;
protected ResourceGenerator $resourceGenerator;
protected int $itemsPerPage;
public function __construct(
array $config,
SnapshotServiceInterface $snapshotService,
HalResponseFactory $halResponseFactory,
ResourceGenerator $resourceGenerator
) {
$this->snapshotService = $snapshotService;
$this->halResponseFactory = $halResponseFactory;
$this->resourceGenerator = $resourceGenerator;
}
public function handle(ServerRequestInterface $request): ResponseInterface
{
$paramsQuery = $request->getQueryParams();
$paramsRoute = $request->getAttributes();
$params = array_merge($paramsQuery, $paramsRoute);
$itemsPerPage = (array_key_exists('itemsPerPage', $params)) ? (int)$params['itemsPerPage'] : $this->itemsPerPage;
$query = $this->snapshotService->getBy($params);
$paginator = new SnapshotListCollection($query->setMaxResults($itemsPerPage));
$resource = $this->resourceGenerator->fromObject($paginator, $request);
return $this->halResponseFactory->createResponse($request, $resource);
}
}
我可能需要一种方法来告诉教义如何补充我的 SnapshotEntity。我读过一个应该附加到 Doctrine 监听器的“生命周期事件”。但是我正在看的所有教程都是用 Symfony 编写的。我如何告诉学说/mezzio/hal 根据不同的路线和使用序列化程序来补充我的实体?有人可以指出我正确的方向吗?
非常感谢!