Symfony 4-KnpPaginator捆绑包“找不到服务,即使它存在于应用程序的容器中” [英] Symfony 4 - KnpPaginator Bundle "service not found, even though it exists in app's container"
问题描述
我一直在学习教程,所有说明都表明它的使用方法完全相同,但是在Symfony 4中似乎不起作用。是否有我在忽略的东西或捆绑包完全不兼容?
I have been following tutorials, and all instructions show it's done the exact same way, but it doesn't seem to work in Symfony 4. Is there something I'm overlooking or is the bundle simply incompatible?
我跑了:作曲家需要knplabs / knp-paginator-bundle
多亏了Flex,它已自动加载到 bundles.php
中。
It was loaded automatically into bundles.php
, thanks to Flex.
将以下内容插入 config / services.yaml
:
knp_paginator:
page_range: 5 # default page range used in pagination control
default_options:
page_name: page # page query parameter name
sort_field_name: sort # sort field query parameter name
sort_direction_name: direction # sort direction query parameter name
distinct: true # ensure distinct results, useful when ORM queries are using GROUP BY statements
template:
pagination: KnpPaginatorBundle:Pagination:twitter_bootstrap_v3_pagination.html.twig # sliding pagination controls template
sortable: KnpPaginatorBundle:Pagination:sortable_link.html.twig # sort link template
试图在控制器中使用以下内容:
Tried to use the following in the controller:
$paginator = $this->get('knp_paginator');
并出现以下错误:
找不到服务 knp_paginator:即使它存在于应用程序的容器中, App\Controller\PhotoController内部的容器也是一个较小的服务定位器,只知道教义, form.factory, http_kernel, request_stack, router, security.authorization_checker, security.token_storage, serializer, session和 twig服务。除非您需要额外的惰性,否则请尝试使用依赖项注入。否则,您需要使用 PhotoController :: getSubscribedServices()进行声明。
Service "knp_paginator" not found: even though it exists in the app's container, the container inside "App\Controller\PhotoController" is a smaller service locator that only knows about the "doctrine", "form.factory", "http_kernel", "request_stack", "router", "security.authorization_checker", "security.token_storage", "serializer", "session" and "twig" services. Unless you need extra laziness, try using dependency injection instead. Otherwise, you need to declare it using "PhotoController::getSubscribedServices()".
推荐答案
您必须扩展 Controller
而不是 AbstractController
类:
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class MyController extends Controller
{
public function myAction()
{
$paginator = $this->get('knp_paginator');
或最好离开 AbstractController
并注入 knp_paginator
服务变成您的操作:
or better leave AbstractController
and inject knp_paginator
service into your action:
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Knp\Component\Pager\PaginatorInterface;
class MyController extends AbstractController
{
public function myAction(PaginatorInterface $paginator)
{
$paginator->paginate()...
}
这篇关于Symfony 4-KnpPaginator捆绑包“找不到服务,即使它存在于应用程序的容器中”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!