Symfony 4 - KnpPaginator Bundle “service not found, even though it exists in app's container”

后端 未结 4 779
青春惊慌失措
青春惊慌失措 2021-01-12 00:01

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 i

相关标签:
4条回答
  • 2021-01-12 00:14

    In my case i'm using symfony 4.3, I just injected the class to the methods as an argument and i'm done.

    public function list(ProductManager $productManager)
    { 
       $products = $productManager->prepareProducts(); 
       return $products;
    }
    
    0 讨论(0)
  • 2021-01-12 00:17

    In my case I use AbstractController and as malcolm says, it is beter to inject the service directrly in your action, even so, I call a method several times and I think that overwrite getSubscribedServices is clener for my porpuse.

    public static function getSubscribedServices(): array
    {
        $services = parent::getSubscribedServices();
        $services['fos_elastica.manager'] = RepositoryManagerInterface::class;
        $services['knp_paginator'] = PaginatorInterface::class;
    
        return $services;
    }
    
    private function listHandler(Search $search, Request $request, int $page): Response
    {
        //...
        $repository = $this->container->get('fos_elastica.manager')->getRepository(Foo::class);
        //...
    
    }
    
    0 讨论(0)
  • 2021-01-12 00:25

    As it says in the documentation. You must extend the base Controller class, or use dependency injection instead https://symfony.com/doc/current/service_container.html#service-parameters

    0 讨论(0)
  • 2021-01-12 00:29

    You have to extend Controller instead of AbstractController class:

    use Symfony\Bundle\FrameworkBundle\Controller\Controller;
    
    class MyController extends Controller
    {
    
        public function myAction()
        {
            $paginator  = $this->get('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()...
        }
    
    0 讨论(0)
提交回复
热议问题