6

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?

Michał Powaga
  • 22,561
  • 8
  • 51
  • 62
MingalevME
  • 1,827
  • 1
  • 22
  • 19
  • 1
    Similar question with good answer [Symfony2 global functions](http://stackoverflow.com/questions/10336401/symfony2-global-functions). – Michał Powaga Jun 13 '13 at 11:29

2 Answers2

7

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.

Elnur Abdurrakhimov
  • 44,533
  • 10
  • 148
  • 133
0

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.

Vladislav Rastrusny
  • 29,378
  • 23
  • 95
  • 156