在我自己的服务中使用 knp_paginator [英] Using knp_paginator within my own service

查看:19
本文介绍了在我自己的服务中使用 knp_paginator的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在自己的服务中使用 knp_paginator,但出现此错误

I am trying to use the knp_paginator within my own service but i get this error

CheckExceptionOnInvalidReferenceBehaviorPass.php 第 58 行中的 ServiceNotFoundException:服务paginatorservice"依赖于不存在的服务knp_paginator".

ServiceNotFoundException in CheckExceptionOnInvalidReferenceBehaviorPass.php line 58: The service "paginatorservice" has a dependency on a non-existent service "knp_paginator ".

这是我的服务:

namespace CommonBundle\Service;

use Doctrine\ORM\EntityManager;

class PaginatorService
{

  public function paginate($query, $pageLimit, $pageNumber)
  {

    $paginator = $this->get('knp_paginator');
    $pagination = $paginator->paginate(
        $query,
        $request->query->getInt('page', $pageNumber),
        $pageLimit 
    );

    return $pagination;
  }

}

我的 service.yml:

my service.yml:

paginatorservice:
    class: CommonBundle\Service\PaginatorService
    arguments: 
        entityManager: [ "@doctrine.orm.entity_manager", "@knp_paginator "]

分页器在我的控制器中工作正常,但我想把它变成一个服务,这样我就可以重用代码.

The paginator works fine in my controller but i want to make it a service so i can reuse the code.

推荐答案

我想通了.

在 service.yml 中,我必须传递 3 个参数,entitymanager"、knp_paginator"和request_stack",因为 request 将在服务中使用.

I the service.yml I have to pass 3 arguments, 'entitymanager', 'knp_paginator' and 'request_stack' since request will be used in the service.

paginatorservice:
    class: CommonBundle\Service\PaginatorService
    arguments: [ "@doctrine.orm.entity_manager", "@knp_paginator","@request_stack"]

我的服务类现在看起来像这样.

My service class now looks like this.

namespace CommonBundle\Service;

use Doctrine\ORM\EntityManager;
use Symfony\Component\HttpFoundation\RequestStack;

class PaginatorService
{

    private $em;
    private $paginator;
    protected $requestStack;

    public function __construct(EntityManager $em, $paginator,RequestStack $requestStack)
    {
        $this->em = $em;
        $this->paginator = $paginator;
        $this->requestStack = $requestStack;
    }

    public function paginate($query, $pageLimit, $pageNumber)
    {
        $request = $this->requestStack->getCurrentRequest();

        $pagination = $this->paginator->paginate(
            $query,
            $request->query->getInt('page', $pageNumber),
            $pageLimit 
        );

        return $pagination;
    }

}

这篇关于在我自己的服务中使用 knp_paginator的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆