【问题标题】:how to use knpPaginatorBundle with rest api?如何将 knpPaginatorBundle 与 rest api 一起使用?
【发布时间】:2017-07-22 19:45:11
【问题描述】:

我尝试使用

公共函数listeleAction(请求$request) { $em=$this->getDoctrine()->getManager();

    $yasam_list=$em->getRepository("VanBundle:Yasam")->findAll();

    if (count($yasam_list)>0)
    {
    $yanit=array();
    foreach ($yasam_list as $meta)
    {
        $new_yasam=array();
        $new_yasam['id']=$meta->getId();
        $new_yasam['adi']=$meta->getAdi();
        $new_yasam['adres']=$meta->getAdres();
        $new_yasam['kategori_id']=$meta->getKategori()->getAdi();
        array_push($yanit,$new_yasam);
    }
        $paginator=$this->get('knp_paginator');

        $result= $paginator->paginate(
            $yanit,
            $request->query->getInt('page',1),
            $request->query->getInt('limit',10)
        );

    }else{
        $yanit["success"] = 0;
  $response["message"] = "Bu kategoriye en kısa sürede veri eklenecektir. ";
    }

    $response=new Response(json_encode(array('yasamlar' =>$result),JSON_UNESCAPED_UNICODE));
    $response->headers->set('Content-type','application/json; charset=utf-8');
    $response->setStatusCode(200);
    return $response;
}

我的 json 输出

{
"yasamlar": {}
}

我该如何解决这个问题?谢谢大家

【问题讨论】:

  • 为什么不在教义查询上使用分页?

标签: symfony knppaginator


【解决方案1】:

我解决了

public function indexAction(Request $request)
    {

        $em=$this->getDoctrine()->getManager();
        //listelenecek bütün Yasam
        $yasam_list=$em->getRepository("VanBundle:Yasam")->findAll();



        $pager=$this->get('knp_paginator');
        $paginated=$pager->paginate($yasam_list,$request->query->getInt('page',1), $request->query->getInt('limit',10));

        $factory=new KnpPaginatorFactory();
        $collection=$factory->createRepresentation($paginated,new Configuration\Route('yasamjson_index'),array()); 

        $serializer = $this->get('jms_serializer');
        $data = $serializer->serialize([
            'meta' => $collection,
            'data' => $paginated->getItems()
        ], 'json');


       return new Response($data);

    }

【讨论】:

    【解决方案2】:

    在进行分页之前,有几点建议:

    • KnpPaginatorBundle 与理论查询生成器一起使用。运行完整的查询并根据结果进行分页无助于提高性能。
    • 对于 REST API,您可以使用FosRestBundle。只需少量配置,您就不必进行json_encode、设置Content-TypeStatus Code
    • 如果您不想使用FosRestBundle。探索并尝试使用 JsonResponse 而不是 Response 作为回报。

    现在,关于将 KnpPagination 信息传递给 API:

    如果您使用的是FosRestBundle,则可以使用JMSSerializerBundle,它将帮助您将实体信息解析为JSON 以获取API 响应。您可以进一步选择要公开的属性。分页数据会被自动解析。

    否则,您只需要遍历 KNPPaginator $result 对象,您可以从教义查询构建器中获得该对象,并将分页和数据分别发送到 JsonResponse

    如果您需要代码 sn-p,请告诉我。

    希望这会有所帮助!

    【讨论】:

    • 我不使用 FosRestBundle
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-16
    • 1970-01-01
    • 2014-02-26
    相关资源
    最近更新 更多