MingalevME
MingalevME

Reputation: 1975

Include User Custom Functions Best Practice in Symfony2

I am a newbie in Symfony2 and I can't understand where I should make includes with my custom cross-projects functions (e.g. array_merge_overwrite, array_last, etc.)? I use both types of apps: web (MVC) and console (extends ContainerAwareCommand).

Or there is another "right way" for this?

Upvotes: 6

Views: 2414

Answers (2)

Elnur Abdurrakhimov
Elnur Abdurrakhimov

Reputation: 44831

Create a service and put your common functionality in it. For example, you can name it ArrayService and register it in the container as array.service. You can then access this service from controllers via

$this->get('array.service');

and from commands via

$this->getContainer()->get('array.service');

So, your code will look something like this:

$element = $this->get('array.service')->last($array); // or ->arrayLast($array)

If you need the same functionality across several projects, make a bundle with that service and add it to the deps file of each project. Then it will be installed when you run the bin/vendors install script.

Upvotes: 7

Vladislav Rastrusny
Vladislav Rastrusny

Reputation: 29965

You can convert your functions to static methods of some class to make them autoloadable. Or... well... Place them where you want and require() from where you need them every time.

Upvotes: 0

Related Questions