1

I would like to know what is the best way to create a global function in Symfony 3.

I'll provide an example: On my website, you can subscribe to the newsletter. When you do, it sends you an email to thank you. The user can do this on many pages.

So I would like to create it once, and use the sending mail function in all the controllers that need it.

Do I have to create it as a class in the app, or do I have to create a bundle specially for it?

I found this answer, but not sure it's the best: Symfony2 global functions

Cave Johnson
  • 6,499
  • 5
  • 38
  • 57
Pierre
  • 490
  • 1
  • 7
  • 26
  • 1
    I would definitely stick the the answer to the question you linked to. My general rule is to have a service if the function has any (at all) dependency to other functionalities (e.g. other services) and if it does not then utility function {{public static function}} would do just fine. – Jovan Perovic Feb 22 '17 at 08:21
  • 1
    Perfect, this is the answer that I needed, thanks you ! Does it matter to have a lot a service, even if they all do 1 or 2 functions ? Or is it better to create one which contains all functions ? – Pierre Feb 22 '17 at 08:31
  • 1
    @DesTunk It is better to have a lot of services with few responsabilities. You will improve your code testability et maintainability. Exemple: NewsletterMailSender UserProvider COmmandValidator .... – goto Feb 22 '17 at 09:32
  • @Destunk: The services are instantiated on the fly, so up until you actually use it, the number of services (memory consumption wise) is not relevant. But, I agree with goto, you should probably have many smaller services with their own responsibility... – Jovan Perovic Feb 22 '17 at 12:04

1 Answers1

4

The best way to do it is Services and Service Container. Just create the service you need and either inject it into controller or use $this->get('your.service.name')->... in controller.

E.K.
  • 1,045
  • 6
  • 10