Code placement in Symfony (Service / Repository)

118 Views Asked by At

Using Symfony 6, I have an entity Article, which has Cat(egories). I would like to get the url of a Cat like this:

        {% for item in data.body.article.cats %}
          <li><a href="{{ item.url }}">{{ item.cat }}</a></li>
        {% endfor %}

But Cat->url isn't a field in the database, it's a generated value.

My questions:

  • I suppose it's not right to create a function getURL() in the Entity Cat, since it's not a DB field. So I should probably put that function in CatService.php or in CatRepository.php. In which file does it go? (When do you use Service and when Repository?)
  • How do I call that function from the twig file?
  • How do I use the current Cat object in that function?

Thanks!

Googled, but I can't really find the difference between Service and Repository.

1

There are 1 best solutions below

2
Dan On

You can create a new controller and route for Category entity to list or read, you don't say what you will do and use the path() function of twig to generate the url. You can read more about path funtion from here https://symfony.com/doc/6.4/reference/twig_reference.html#path. Your twig should looks like:

        {% for item in data.body.article.cats %}
          <li><a href="{{ path('your_category_route', {category: item.id}) }}">your category name</a></li>
          {# or whatever is your relation to category, you don't give any info about relations #}
        {% endfor %}

And your route should looks like:

your_category_route:
    path: /url-path/{category}/
    controller: YourControllerPath::method