I have been advice not to use the singleton pattern for my data base class. I have not fully understand what are the cons to it, anyway there seems to be agreement in this point so I follow the rule.
But, is sharing instances of classes a bad habit in PHP in general? Which is best from the two examples provide here? I am using in fact the singleton pattern with the first approach?
//semi-pseudo Code
Class DB extends mysqli{
//
}
Class A {
$db; //Of type Class DB, initialized in the constructor.
//In some method
//Should I do this, so sharing the data base connection?
$b = new DB( $db );
// OR
// Should I instantiate a new instance?
$newDb = new DB();
$b = new B ($newDb);
}
Class B {
$db;//Of type Class DB initialized in the constructor.
I have a Class DB being a data base extension..
I have Class A with a member of type DB.
Class A needs to create an instance of Class B, which in turn also has a member of type DB.
I'm using the Dependency Injection pattern so A should pass a DB instance to B.
Should I instantiate a new DB instance to pass to B, or can I just pass a reference to A's DB instance.
There's nothing wrong with using the Singleton pattern in PHP, like any language, too much of anything likely indicates poor design.
That said, Singleton is well suited to database access. Has anyone justified why it's supposedly a bad idea?
The main argument against Singleton is difficulty to test because you can't mock them with unit test suites. Personally I try to avoid mock objects in my tests (especially w/ PHPUnit), so it usually doesn't matter.
Should I instantiate a new DB instance to pass to B, or can I just pass a reference to A's DB instance.
Of course you have to pass a reference of A's DB instance to B class.