Top Banner
The Singleton Dilemma Frank Sons Senior PHP Engineer CTD
22
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: The Singleton Dilemma

The Singleton Dilemma

Frank SonsSenior PHP Engineer CTD

Page 2: The Singleton Dilemma

The Singleton Dilemma

2

What is a Singleton?

What is the problem?

What is the solution to this dilemma?

Page 3: The Singleton Dilemma

Singleton? What‘s that?

3

Page 4: The Singleton Dilemma

Singleton? Tell me more…

4

Probably best known design pattern

Only one instance of a class at any time

Global access to that single instance

Page 5: The Singleton Dilemma

How to implement a Singleton in PHP?

5

Page 6: The Singleton Dilemma

How to use the Singleton?

6

Page 7: The Singleton Dilemma

So, it is really cool, isn‘t it?

7

Page 8: The Singleton Dilemma

Singleton and PHP are no friends

8

Singleton: unique instance for application

PHP: Shared-Nothing architecture

Dilemma: instance only unique for request

Page 9: The Singleton Dilemma

Singleton has even more problems

9

Dependency hiding

Globals are bad, singleton is a global

No Unit Testing possible

Page 10: The Singleton Dilemma

Is there a solution?

10

Page 11: The Singleton Dilemma

Solution: Just create one!

11

Code Convention: just create one

Trust your Team members!

Page 12: The Singleton Dilemma

Solution: Dependency Injection

12

Create one instance and „inject“ it

Objects should be loosely coupled

Don‘t create objects in regular classes

„Ask, don‘t look“

Page 13: The Singleton Dilemma

Solution: Dependency Injection

13

Page 14: The Singleton Dilemma

Solution: Factory

14

Encapsulates object creation

Different factories for different lifetimes

Handles object lifetimes

Page 15: The Singleton Dilemma

Solution: Factory

15

Page 16: The Singleton Dilemma

Solution: PHP application lifetime

16

Cache or Session for „application“ lifetime

Factory can handle Cache or Session

Page 17: The Singleton Dilemma

„Friends don‘t let friends do Singleton“

17

Page 18: The Singleton Dilemma

Benefits!

18

Unit Testing is possible!

Easy object creation!

Better lifetime handling!

Easy to change dependencies!

Page 19: The Singleton Dilemma

And about the good Singleton…

19

Page 20: The Singleton Dilemma

The only good Singleton…

20

Page 21: The Singleton Dilemma

Thank you!

21

Page 22: The Singleton Dilemma

Find us on

Bigpoint GmbHFrank Sons

Senior Software Engineer CTD

Drehbahn 47-4820354 Hamburg

Germany

Tel +49 40.88 14 13 - 0Fax +49 40.88 14 13 - 11

[email protected]

23