Singleton pattern
On 2 September 2011 in PelbagaiSingleton class is class that allow only one instance of its class to be instantiated.
A lot of examples I see the way to implement singleton pattern whether:
1. Extends a base singleton class
2. Each class apply singleton pattern (get_instance() method, has static $instance attribute)
3. Using registry pattern where one dedicated class act as the singleton instances manager
Well, things shouldn’t get too hard. Here, I will use the combination of registry pattern and singleton in just a function
function o($class) { static $instances; if (!isset($instances[$class]) || !$instances[$class] instanceof $class) { $instances[$class] =& new $class(); } return $instances[$class]; }
To use it:
o('db')->query(...); o('db')->fetch(); o('singleton_class')->do_something();
Related posts:
-
New PHP
-
Page Controller Pt.2
-
OOP the right way
-
PHP Data Validation
-
PHP timezone handling
-
PHP async request with auth
-
Formula E bakal dianjurkan di Kuching?
-
phpBB SEO Ultimate URL backslash in URL
-
Cloudflare & phpBB3
-
PHP Hooks System
Filed under Pelbagai with tags Idea, PHP, Registry pattern, Singleton
Thanks for sharing your info. I really appreciate
your efforts and I will be waiting for your further write ups thank you once again.