0

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

CheckExceptionOnInvalidReferenceBehaviorPass.php 第 58 行中的 ServiceNotFoundException:服务“paginatorservice”依赖于不存在的服务“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;
  }

}

我的服务.yml:

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

分页器在我的控制器中工作正常,但我想让它成为一项服务,以便我可以重用代码。

4

2 回答 2

3

您应该将它们注入服务的 __construct 中:

$private $em;
$private $paginator;
public function __contruct($em, $paginator){
   $this->em = $em;
   $this->$paginator = $paginator;
} 

并改变:

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

希望能帮助到你。

于 2017-08-25T08:03:57.400 回答
2

我想到了。

在 service.yml 中,我必须传递 3 个参数,“entitymanager”、“knp_paginator”和“request_stack”,因为请求将在服务中使用。

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

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

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;
    }

}
于 2017-08-25T09:17:28.427 回答