I am using Symfony2 lately and I keep wondering when I should create a service and when I should create a class.
For example I do have this little snippet function that is a very reusable piece of code. So because of that I do not want that piece of code in my controller. Meaning that I would want to use it anywhere in my bundle.
It's very simple, but it basically generates a full url for me based on a slug/path. Now please note that this could be anything else for example a customStringGenerator() or what so ever.
The snippet:
public function generateUrlFromPath(Request $request, $path)
{
return $request->getScheme() . '://' . $request->getHttpHost() . $request->getBasePath() . $path;
}
Now I could make some sort of Toolkit or UrlHelper class and define it as a service so I can easily inject the Request object, but it seems overdone for me to create a service for such a simple method.
What would anyone suggest in this case? What would you guys do when you have created reusable functions?
Thanks for your help so far.
For reusability, I use:
Services (When I need to inject other dependencies through constructor), so you don't have to do it manually everytime.
Helper controller, which my controllers extend.
Classes with public static functions.
Traits (PHP >= 5.4), when you need to share same methods in a few classes, to help overcome single class inheritance limitation.
For your function up there, I would personally make a protected function inside a Helper controller, but a service would be ok too, even it is such a small piece of code. You might end up writing more code to that service later.
You can create a Utility class or even a Utility Bundle with your reusable codes. See the following links with instructions:
- Symfony 2 - Where should I put a utility class?
- Where do I put classes in Symfony that are neither Controllers nor models?
Depending on your case, you can add a 'Helper' subfolder (another namespace) to your bundle and use its methods from there. This is of course if you only plan to re-use that code from inside that Bundle.