2

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

4
  • 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. Commented Feb 22, 2017 at 8: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 ? Commented Feb 22, 2017 at 8: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 .... Commented Feb 22, 2017 at 9: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... Commented Feb 22, 2017 at 12:04

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.