我在使用 JMS 序列化器排除一些 KNP 分页器属性时遇到问题。
首先,这包含在 composer.json
...
"jms/serializer-bundle": "~0.13",
"knplabs/knp-paginator-bundle": "2.4.*@dev",
...
我正在对 CrmContacts 实体进行分页,该实体的排除策略运行良好。我还为 KNP Paginator 添加了 yml 文件,如下所示:
配置.yml
jms_serializer:
metadata:
directories:
KNPPB:
namespace_prefix: 'Knp\\Bundle\\PaginatorBundle'
path: %kernel.root_dir%/Resources/serializer/Knp
在 app/Resources/serializer/Knp 文件夹中,我创建了 Pagination.SlidingPagination.yml:
Knp\Bundle\PaginatorBundle\Pagination\SlidingPagination:
exclusion_policy: ALL
properties:
items:
expose: true
access_type: public_method
accessor:
getter: getItems
type: array
serialized_name:
payload
currentPageNumber:
expose: true
serialized_name:
page
numItemsPerPage:
expose: true
serialized_name:
items
totalCount:
expose: true
serialized_name:
totalItems
这是返回序列化数据的逻辑:
public function getContactsAction(Request $request)
{
$limit = $request->query->getInt('l', 10);
$page = $request->query->getInt('p', 1);
$serializer = $this->get('jms_serializer');
$contacts = $this->getDoctrine()
->getManager()
->getRepository('AcmeContactsBundle:CrmContact')
->getContacts();
$paginator = $this->get('knp_paginator');
$pagination = $paginator->paginate(
$contacts,
$page,
$limit
);
return new Response(
$serializer->serialize(
$pagination,
'json',
SerializationContext::create()->setGroups(['Default'])
),
Response::HTTP_OK,
[
'Content-Type' => 'application/json',
]
);
}
不幸的是,我从 Knp Paginator 获得了所有属性作为回应:
{
"currentPageNumber": 1,
"numItemsPerPage": 10,
"items": [
{
"id": 1,
...
},
{
"id": 2,
...
},
{
"id": 3,
...
}
],
"totalCount": 3,
"paginatorOptions": {
"pageParameterName": "page",
"sortFieldParameterName": "sort",
"sortDirectionParameterName": "direction",
"filterFieldParameterName": "filterField",
"filterValueParameterName": "filterValue",
"distinct": true
},
"customParameters": [],
"route": "acmeContactsGetContacts",
"params": [],
"pageRange": 5,
"template": "KnpPaginatorBundle:Pagination:sliding.html.twig",
"sortableTemplate": "KnpPaginatorBundle:Pagination:sortable_link.html.twig",
"filtrationTemplate": "KnpPaginatorBundle:Pagination:filtration.html.twig"
}