phpsymfonysymfony6

Checking request requirements in PHP Symfony: Do I have to use services? (OOP vs Services in Symfony)


I'm working on my second Symfony project and trying to follow best practices. I've switched from static methods to services for improved readability and potential performance gains. For instance, I have a ResponseService that generates JsonResponse objects from database data. This was handled by a static function in my first project:
Responses::getJsonResponse($entityManager, [...])
--> $responseService->getResponse([...])

My question is: Should everything requiring autowired arguments and frequent use become a service?

For example, I have a RequirementsCheck class that verifies user permissions, mandatory form data, etc. Here's an example controller method:

#[Route('/ajax/matches/start/', name: 'app_ajax_match_start', methods: ["GET"])]
public function app_ajax_match_start(RequestStack $requestStack, EntityManagerInterface $entityManager): JsonResponse|Response
{
  $req = RequirementsCheck::create($requestStack, $entityManager, permissions: [Permission::EDIT_RESULTS], required_types: ["matches" => "array_int"], data_fields: $_GET);
  if(!$req->isAllowed()) return $req->getResponse();
  // [...]
}

As you can see, I directly inject $requestStack and $entityManager. However, creating a service for RequirementsCheck might improve readability and potentially performance. Still, I feel an object-oriented approach might be more suitable.

What are your thoughts? Is there a universally better solution?

PS: Let me know if there's something I can improve in this post. I'm still quite new and might not have followed all guidelines to the best question.

Edit: Here's the current RequirementsCheck class


Solution

  • Should everything requiring autowired arguments and frequent use become a service?

    Very interesting question! Yes! And it exactly works as you ask for, this is in the Symfony documentation:

    Your application is full of useful objects: a "Mailer" object might help you send emails while another object might help you save things to the database. Almost everything that your app "does" is actually done by one of these objects. And each time you install a new bundle, you get access to even more!

    In Symfony, these useful objects are called services[...]

    (from: https://symfony.com/doc/current/service_container.html)

    This should also give you the hint that you should also look for re-using existing services instead of writing (entirely) your own.