Home > Back-end >  add service to my parent of BaseController
add service to my parent of BaseController

Time:08-31

as you know controllers in symfony extends AbstractController i want to add some usual methods in base controller and simply use in my method in controller like $this->validate for example so i created a BaseController that extends AbstractController . the issue is how can i use my ValidationService in BaseController? i have to add construct in BaseController and so again pass parent Constructor. another solution is get my ValidationService in BaseController like $this->container->get("my.validation.service") that gives me error like this :

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

what is the best practice for this?

CodePudding user response:

It sounds like you should be using constructor injection and standard PHP inheritance here (this uses property promotion from php 8)


namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use App\Service\ValidationService;

class MyCustomBaseController extends AbstractController
{
    public function __construct(private readonly ValidationService $validationService)
    {
    }
}
namespace App\Controller;

use App\Controller\MyCustomBaseController;

class MyNormalController extends MyCustomBaseController
{
    public function foo()
    {
        $this->validationService->foo();
    }
}
  • Related