Best Practice on PHP Singleton Classes

Best practice on PHP singleton classes

An example singleton classes in php:

Creating the Singleton design pattern in PHP5 : Ans 1 :

Creating the Singleton design pattern in PHP5 : Ans 2 :

Singleton is considered "bad practice".

Mainly because of this: How is testing the registry pattern or singleton hard in PHP?

  • why are singleton bad?

  • why singletons are evil?

  • A good approach: Dependency Injection

  • Presentation on reusability: Decouple your PHP code for reusability

  • Do you need a dependency injection container

  • Static methods vs singletons choose neither

  • The Clean Code Talks - "Global State and Singletons"

  • Inversion of Control Containers and the Dependency Injection pattern

Wanna read more? :

  • What are the disadvantages of using a PHP database class as a singleton?

  • Database abstraction class design using PHP PDO

  • Would singleton be a good design pattern for a microblogging site?

  • Modifying a class to encapsulate instead of inherit

  • How to access an object from another class?

  • Testing Code That Uses Singletons

A Singleton decision diagram (source):

Singleton Decision Diagram

Singleton or Static? Best practice For php?

The choice between a singleton pattern and a "new instance with static" doesn't really resolves the dependency injection question.

However I suggest you to use the singleton design pattern to access your Request object.

Why ?

  • This pattern fits your needs, it respects the "one and unique object instance" for your Request class.
  • Developers should be aware of this structure, that's a proof of sustainability.
  • Encapsulation
  • Design patterns are 99% "best pratices"

And the dependency injection ?

From my experience, I suggest you to take a look at the factory design pattern.


You'll centralize the creation of your objects and the dependencies injection will be a lot easier and cleaner.



Of course, this is only my way to code, I don't pretend to have the best practices and this should be discussable.

Hope this will help you.

Creating the Singleton design pattern in PHP5

/**
* Singleton class
*
*/
final class UserFactory
{
private static $inst = null;

// Prevent cloning and de-serializing
private function __clone(){}
private function __wakeup(){}


/**
* Call this method to get singleton
*
* @return UserFactory
*/
public static function Instance()
{
if ($inst === null) {
$inst = new UserFactory();
}
return $inst;
}

/**
* Private ctor so nobody else can instantiate it
*
*/
private function __construct()
{

}
}

To use:

$fact = UserFactory::Instance();
$fact2 = UserFactory::Instance();

$fact == $fact2;

But:

$fact = new UserFactory()

Throws an error.

See http://php.net/manual/en/language.variables.scope.php#language.variables.scope.static to understand static variable scopes and why setting static $inst = null; works.

What is singleton in PHP?

A singleton is a particular kind of class that, as you correctly said, can be instantiated only once.

First point: it isn't a PHP related concept but an OOP concept.

What "instantiated only once means?" It simply means that if an object of that class was already instantiated, the system will return it instead of creating new one.
Why? Because, sometimes, you need a "common" instance (global one) or because instantiating a "copy" of an already existent object is useless.

Let's consider for first case a framework: on bootstrap operation you need to instantiate an object but you can (you have to) share it with other that request for a framework bootstrap.

For the second case let's consider a class that has only methods and no members (so basically no internal state). Maybe you could implement it as a static class, but if you want to follow design patterns, consider AbstractFactory) you should use objects. So, having some copy of the same object that has only methods isn't necessary and is also memory-wasting.

Those are two main reason to use singleton to me.

Behaviour of private constructor in singleton design pattern in PHP

You can only initialize it thru Model_Acl::getinstance().

But yes, it will work.

Singleton is not considered a good practice, you should consider Dependency Injection.

http://fabien.potencier.org/article/11/what-is-dependency-injection.

More information about php Singletons

Best practice on PHP singleton classes

Singleton pattern example in PHP

Look at "Example #5 Example use of static variables" here:
http://php.net/manual/en/language.variables.scope.php#language.variables.scope.static

"Now, $a is initialized only in first call of function and every time the test() function is called it will print the value of $a and increment it."

Best practice to implement static class inheritance? (singleton)

The Singleton pattern in PHP is something like this:

class Singleton {
private static $instance = null;

// Constructor is private, so class cannot be instantiazed from outside
private function __construct() {
}

public static function getInstance() {
if (static::$instance === null) {
static::$instance = new Singleton();
}
return static::$instance;
}

public static function test() {
echo 'Singleton::test()';
}

public function __sleep() {
throw new Exception('Serialization is not alowed.');
}

public function __wakeup() {
throw new Exception('Serialization is not alowed.');
}

public function __clone() {
throw new Exception('Cloning is not alowed.');
}
}

For you is important that keyword static, then this:

class B extends Singleton {
public static function test2() {
echo 'B::test2()';
}
}

$b = B::getInstance();
B::test();
B::test2();
// Singleton::test()
// B::test()

Is this you looking for?

Is there a use-case for singletons with database access in PHP?

Okay, I wondered over that one for a while when I first started my career. Implemented it different ways and came up with two reasons to choose not to use static classes, but they are pretty big ones.

One is that you will find that very often something that you are absolutely sure that you'll never have more than one instance of, you eventually have a second. You may end up with a second monitor, a second database, a second server--whatever.

When this happens, if you have used a static class you're in for a much worse refactor than if you had used a singleton. A singleton is an iffy pattern in itself, but it converts fairly easily to an intelligent factory pattern--can even be converted to use dependency injection without too much trouble. For instance, if your singleton is gotten through getInstance(), you can pretty easily change that to getInstance(databaseName) and allow for multiple databases--no other code changes.

The second issue is testing (And honestly, this is the same as the first issue). Sometimes you want to replace your database with a mock database. In effect this is a second instance of the database object. This is much harder to do with static classes than it is with a singleton, you only have to mock out the getInstance() method, not every single method in a static class (which in some languages can be very difficult).

It really comes down to habits--and when people say "Globals" are bad, they have very good reasons to say so, but it may not always be obvious until you've hit the problem yourself.

The best thing you can do is ask (like you did) then make a choice and observe the ramifications of your decision. Having the knowledge to interpret your code's evolution over time is much more important than doing it right in the first place.

php singleton database connection, is this code bad practice?

Singletons are bad news.

  • They introduce global state into a program. Most programmers should be familiar with why global state is bad.
  • They introduce tight coupling between the singleton and any class that uses it. This means you can't reuse the classes in question without reusing the singleton too.
  • They make unit testing of classes that depend on the singleton problematic because you can't easily replace the singleton with a mock.
  • They encourage a coding style where classes attempt to resolve their own dependencies. This is bad because it can reduce clarity regarding what dependencies the class has.
  • PHP has a Share Nothing Architecture, meaning that PHP singletons aren't really singletons at all, there can be multiple instances alive at any one time (one per open request).
  • What happens if you suddenly discover at some later date that you actually need more than one of the resource that's being provided by the singleton? It's a more common scenario than you might think

You're better off looking at dependency-injection instead, as it resolves the above issues.



Related Topics



Leave a reply



Submit