the singleton dilemma

22
The Singleton Dilemma Frank Sons Senior PHP Engineer CTD

Upload: frank-sons

Post on 13-Jul-2015

527 views

Category:

Technology


0 download

TRANSCRIPT

The Singleton Dilemma

Frank SonsSenior PHP Engineer CTD

The Singleton Dilemma

2

What is a Singleton?

What is the problem?

What is the solution to this dilemma?

Singleton? What‘s that?

3

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

How to implement a Singleton in PHP?

5

How to use the Singleton?

6

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

7

Singleton and PHP are no friends

8

Singleton: unique instance for application

PHP: Shared-Nothing architecture

Dilemma: instance only unique for request

Singleton has even more problems

9

Dependency hiding

Globals are bad, singleton is a global

No Unit Testing possible

Is there a solution?

10

Solution: Just create one!

11

Code Convention: just create one

Trust your Team members!

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“

Solution: Dependency Injection

13

Solution: Factory

14

Encapsulates object creation

Different factories for different lifetimes

Handles object lifetimes

Solution: Factory

15

Solution: PHP application lifetime

16

Cache or Session for „application“ lifetime

Factory can handle Cache or Session

„Friends don‘t let friends do Singleton“

17

Benefits!

18

Unit Testing is possible!

Easy object creation!

Better lifetime handling!

Easy to change dependencies!

And about the good Singleton…

19

The only good Singleton…

20

Thank you!

21

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