Where to put the business logic in symfony 4+? [closed]

  business-logic, entity, php, symfony, symfony4

Obviously I want to follow the best practices and keep the controllers and entitys lean. But I’m confused about where to put the business logic of my application. Neither the official answer to this problem nor the answers on StackOverflow (mostly for older Symfony versions) seem to help.

Let’s dive in. Here’s a subset of my entitys:

- id
- name
- sensors

- id
- project
- location
- measurement_values

- sensor
- datetime
- value


So in a the app’s dashboard I list Projects. Projects have Sensors and MeasurementValues. Besides each project name, I want to display some values “calculated” from measurement values. E.g. a warning if the youngest measurement value is older than x hours. So in the template I want to do something like this:

{% for project in projects %}
    {{ project.name }}{{ project.measurements_too_old ? ' - Warning' : '' }}<br>
{% endfor %}


Where would I implement this measurement_too_old function? For sure I could put the measurement_to_old function into a service, but how would I pass this to the template alongside the list of projects? Currently the controller for the dashboard looks like this:

     * @Route("/", name="project_index", methods={"GET"})
    public function index(ProjectRepository $projectRepository): Response
        return $this->render('project/index.html.twig', [
            'projects_active' => $projectRepository->findBy(['active' => true]),
            'projects_inactive' => $projectRepository->findBy(['active' => false]),

I’m not sure how to pass the additional info needed to the template. What’s the right approach?

Is using custom twig filters (as proposed here) a proper solution to this problem? My gut feeling says no.

This is just one example of many of the same use cases I struggle with in porting my plain PHP app to Symfony. In my plain PHP app I’d simply extend the respective class to include the method needed. Obviously 8 years ago when I wrote the app, separating the storage from the business logic wasn’t a big worry of mine 😀

Source: Symfony Questions