8

I'm moving my old codebase to the Symfony 2.2 framework.

In my old code, my Article entity has had a method getUrl(), which was returning a URL for current article.

In Symfony i have to use Router service to generate such an URLs.

I can't access Router from inside the Entity, cause it's a bad practice and not really supported by the framework.

I can call the router from the Twig template itself using Twig helper path() and provide all the arguments (from the Article instance) needed to construct the URL. But this approach is not very good, cause if i'll decide to change URL formatting rules - i will have to find all this calls and rewrite them (not very DRY).

I really want to save the business-logic encapsulation here and not to pull all the guts to the view layer.

How should i proceed in this situation?

Slava Fomin II
  • 26,865
  • 29
  • 124
  • 202

1 Answers1

11

Create an ArticleManager class in your service layer, and handle any business logic there. You can pass the router to it through dependency injection.

For your example, ArticleManager would have a getUrl(Article $article) method which would use the router instance (that you either injected through __construct or a separate setter method) to generate the Url based on properties of $article, and return it.

This method will ensure that your business logic doesn't pollute the view or controller layers.

Be sure to read up on the Service Container docs.

Steven Mercatante
  • 24,757
  • 9
  • 65
  • 109
  • Thanks Arms! I was thinking about this approach, just needed a confirmation from someone more experienced ) I'm not sure that i really comfortable with managing model entities from some other class, but looks like this is only viable option. – Slava Fomin II Mar 15 '13 at 13:27
  • If you're coming from an Active Record ORM, this definitely feels like a foreign approach. But over time you'll appreciate the separation of concerns and wonder how you ever managed before ;-) – Steven Mercatante Mar 15 '13 at 14:45
  • @SlavaFominII This is a good solution but, if you have same "model" object, pool them into the same Manger or you'll have a manager (so, a service) for every entity of your application and this, sometimes, isn't desiderable – DonCallisto Mar 15 '13 at 15:13
  • @DonCallisto That's the beauty of these manager objects - while typically used for managing one entity, there's nothing stopping you from using as many entities as needed to perform business tasks. – Steven Mercatante Mar 15 '13 at 15:48
  • @Arms: No one told that he hasn't to do for particular reason, I only told that if you have a model object that is equiparable with another, is better to create a unique manager. Of course, this is my point of view – DonCallisto Mar 15 '13 at 15:55