|
Location: Web development - PHP License: The Intelliproject Open License (IPOL) Singleton pattern in PHPPosted by Panos KyriakakisImplementation and use of Singleton Pattern in PHP |
Skill: IntermediatePosted: 19/11/2008Views: 704Rating: 4.00 /5Popularity: 1.20 |
| Sign Up to vote for this article |
Not something realy new and not invented by myself, but it is something realy usefull and changed the way i see OOP for ever.
Singleton is one of the many OOP patterns out there, each one of them servers a purpose and Singleton solves a basic issue, having stuff available without carring around variables or using globals.
Lets see a practical case that singleton pattern cames in handy. What we usualy do in the startup proccess of the code is to load configuration and various setting for our application. The common way to do it, is create a class which loads and hold them. Something like the next chunk of code
ok, nothing much. If you instanciate this one you have to carry around the variable to this instance or make it global. Let's make her Singleton.
First of all notice the static variable $instance. This one is static so it is accessible before the class is instantiated and it is common to all instances of the class, ofcource in the same session. This variable is used to hold a pointer to the instance of the class. Even if the initial pointer to the instance comes out of scope, the value of this variable is untached.
Then we have the "magic" method getInstance. That one is also static. Checkes if the static variable (notice self::) has value, this means if the class has been instanciated before, if not creates an instance of the class and makes self::$instance pointing to her. So, when we make the call Settings::getInstance() for first time creates a new object and every other time it returns that object.
To make you believe try the next one:
the result you will get is the unexpected "away".
Now lets make it a little bit more real.
In the bootstrap of our application
Somewhere else, anywhere else in our application now we can access the settings loaded in the bootstrap like this
Isnt it great! The OOP response to global variables!
I hope that even if i didnt make it clear how it works, that I made clear how useful it is.
This article, along with any associated source code and files, is licensed under The Intelliproject Open License (IPOL)
| Panos Kyriakakis
| Panos started coding on a Sinclair ZX-Spectrum +2 in 1987 or 1988, move to pcs and GW-Basic then to CA-Clipper, fortran, pascal, c, VB4, VB5, VB6, asp and landed to PHP about 5 years ago. Those 20 years many small and big project were build. These day he tries to polish and give to public an accounting service for small bussines in Greece. It is in beta version and sales force is setting up. Published a couple open source libs and try to maintain my site. Location: |
Sign up to post message on the article message board!