Where to place business logic - is this a layer of the Symfony 2 model?

I am moving my old code base to the Symfony 2.2 framework.

In my previous code, my article object had a getUrl () method that returned the URL for the current article.

In Symfony, I need to use the Router service to create such URLs.

I cannot access the Router from within Entity, causing it to be bad practice and not supported by the platform.

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 create the URL. But this approach is not very good, because if I decide to change the rules for formatting URLs, I will have to find all these calls and rewrite them (not very DRY ).

I really want to keep the encapsulation of business logic here, rather than pulling all the guts to the presentation layer.

How do I start this situation?

+8
symfony model
source share
1 answer

Create the ArticleManager class at the service level and handle any business logic. You can pass it to the router through dependency injection.

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

This method ensures that your business logic does not pollute the layers of the view or controller.

Be sure to check out the Service Container Docs .

+11
source share

All Articles