3

I've came across a problem in an application I am building and that is: how can I create a single database connection for use across multiple classes?

After reading upon this a little bit, different posts/people seem to be telling me different things. Use of $_GLOBAL or the global keyword would be one way to do it, but that has it's own issues.

Other threads on Stackoverflow have suggested Singletons as a way of doing so, but also stated that it wouldn't be the proper way of achieving a shared property of an instance.

So, what would be the best way of achieving this, say for a Database Controller or a Session Controller?

Polarize
  • 1,005
  • 2
  • 10
  • 27
  • 2
    [Dependency injection](https://en.wikipedia.org/wiki/Dependency_injection) with a container. Look into [Pimple](http://pimple.sensiolabs.org/). – John Conde Jul 09 '16 at 15:13
  • [This post](http://stackoverflow.com/a/16605563/5816907) provides its bests, also DI as johnconde mentioned – Chay22 Jul 09 '16 at 15:20
  • @JohnConde Dependency Injection is perfect and works very well with my application, thanks! Can you write as an answer so I can accept? – Polarize Jul 09 '16 at 17:38

1 Answers1

0

Globals and singletons are way of the past. Dependenci Injection is todays best approach. Of course, there will be many people that wouldn't agree with me, so at the end, choise is yours.

I would recommend using DI implementation from Nette Framework - https://github.com/nette/di Why this one? Because it will do lot of work for you. For example autogenerating of Dependency Injection Container or autogenerating class factories from simple interface.

Tomáš Jacík
  • 645
  • 4
  • 12