The Singleton Dilemma

1,010 views

Published on

Presentation I held internally at Bigpoint about what the main problem with Singleton, especially in PHP, is.

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
1,010
On SlideShare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
11
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

The Singleton Dilemma

  1. 1. The Singleton DilemmaFrank SonsSenior PHP Engineer CTD
  2. 2. The Singleton Dilemma What is a Singleton? What is the problem? What is the solution to this dilemma? 2
  3. 3. Singleton? What‘s that? 3
  4. 4. Singleton? Tell me more… Probably best known design pattern Only one instance of a class at any time Global access to that single instance 4
  5. 5. How to implement a Singleton in PHP? 5
  6. 6. How to use the Singleton? 6
  7. 7. So, it is really cool, isn‘t it? 7
  8. 8. Singleton and PHP are no friends Singleton: unique instance for application PHP: Shared-Nothing architecture Dilemma: instance only unique for request 8
  9. 9. Singleton has even more problems Dependency hiding Globals are bad, singleton is a global No Unit Testing possible 9
  10. 10. Is there a solution? 10
  11. 11. Solution: Just create one! Code Convention: just create one Trust your Team members! 11
  12. 12. Solution: Dependency Injection Create one instance and „inject“ it Don‘t create objects in regular classes Objects should be loosely coupled „Ask, don‘t look“ 12
  13. 13. Solution: Dependency Injection 13
  14. 14. Solution: Factory Encapsulates object creation Handles object lifetimes Different factories for different lifetimes 14
  15. 15. Solution: Factory 15
  16. 16. Solution: PHP application lifetime Cache or Session for „application“ lifetime Factory can handle Cache or Session 16
  17. 17. „Friends don‘t let friends do Singleton“ 17
  18. 18. Benefits! Unit Testing is possible! Better lifetime handling! Easy object creation! Easy to change dependencies! 18
  19. 19. And about the good Singleton… 19
  20. 20. The only good Singleton… 20
  21. 21. Thank you! 21
  22. 22. Bigpoint GmbH Frank SonsSenior Software Engineer CTD Drehbahn 47-48 20354 Hamburg Germany Tel +49 40.88 14 13 - 0 Fax +49 40.88 14 13 - 11 info@bigpoint.net www.bigpoint.net Find us on 23

×