我正在尝试在我自己的服务中使用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;
}
}
我的service.yml:
paginatorservice:
class: CommonBundle\Service\PaginatorService
arguments:
entityManager: [ "@doctrine.orm.entity_manager", "@knp_paginator "]
paginator在我的控制器中工作正常,但我想让它成为一个服务,所以我可以重用代码。
答案 0 :(得分: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"]
希望它有所帮助。
答案 1 :(得分: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;
}
}