Home > OS >  Call function in controller using service symfony 5
Call function in controller using service symfony 5

Time:11-03

I tried to call a function in a controller using service:

#BookManager.php
<?php

 namespace App\Service;

 use App\Entity\BookContent;
 use Doctrine\ORM\EntityManagerInterface;


 class BookManager
 {
protected $entityManager;

public function __construct(EntityManagerInterface $entityManager)
{
    $this->entityManager = $entityManager;
}

public function getBookTitle(string $page){ 
  return $this->entityManager->getRepository(BookContent::class) 
  >findOneBy(["page"=>$page])->getTitle();
 }

In service.yml

....

services:
    book.manager:
    class: App\Service\BookManager
    arguments: ['@doctrine.orm.entity_manager']
    public: true

Finally I call it in Controller ;

$pageName = $this->container->get('request_stack')->getMasterRequest()->get('_route');
    $bookTitle = $this->container->get('book.manager')->getBookTitle($pageName);

But I get this error

Service "book.manager" not found: even though it exists in the app's container, the container inside "App\Controller\HomeController" is a smaller service locator that only knows about the "doctrine", "form.factory", "http_kernel", "parameter_bag", "request_stack", "router", "security.authorization_checker", "security.csrf.token_manager", "security.token_storage", "serializer", "session" and "twig" services. Try using dependency injection instead.

Any idea?

EDIT

it's work when I use dependency injection but only when I do query with $id

$this->entityManager->getRepository(BookContent::class)- 
>findOneById(["id"=>$id])->getTitle();

when I do it with findOneBy(["page"=>$page]) I get this error:

Impossible to access an attribute ("title") on a null variable.

CodePudding user response:

By default Symfony 5 will autowire/auto configure your services. You can remove the book.manager from your service.yaml.

You can then use dependency injection in your controllers to access your services, like this for example:

<?php

namespace App\Controller;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

use App\Service\BookManager; //<-- Add use

class YourController extends AbstractController
{
    /**
    * @Route("/", name="home")
    */
    public function index(Request $request, BookManager $bookManager): Response
    {
        $pageName = $request->attributes->get('_route');
        $bookTitle = $bookManager->getBookTitle($pageName);

        return ...
    }
}
  • Related