So I’m designing a reporting system at work it’s my first project written OOP and I’m stuck on the design choice for the DB class.
Obviously I only want to create one instance of the DB class per-session/user and then pass it to each of the classes that need it. What I don’t know it what’s best practice for implementing this. Currently I have code like the following:-
class db
{
private $user = 'USER';
private $pass = 'PASS';
private $tables = array( 'user','report', 'etc...');
function __construct(){
//SET UP CONNECTION AND TABLES
}
};
class report{
function __construct ($params = array(), $db, $user)
{
//Error checking/handling trimed
//$db is the database object we created
$this->db = $db;
//$this->user is the user object for the logged in user
$this->user = $user;
$this->reportCreate();
}
public function setPermission($permissionId = 1)
{
//Note the $this->db is this the best practise solution?
$this->db->permission->find($permissionId)
//Note the $this->user is this the best practise solution?
$this->user->checkPermission(1)
$data=array();
$this->db->reportpermission->insert($data)
}
};//end report
I’ve been reading about using static classes and have just come across Singletons (though these appear to be passé already?) so what’s current best practice for doing this?
1
Singletons in PHP are quite useless, your instances are created when the script is executed, and die when the script ends, regardless of whether they are singletons or not. This is by design, PHP follows a share nothing architecture.
Just continue doing what you already do, it even has a fancy name: constructor injection. Read up on dependency injection, and if you want to make your constructor a bit more robust, consider type hinting:
class report {
function __construct (array $params = array(), db $db, $user)
{
....
}
...
}
Further reading:
- When is Singleton appropriate? (and it’s dupe: The Singleton Pattern)
- What is so bad about Singletons?
- When is it not appropriate to use the dependency injection pattern?
- What are the benefits of using Dependency Injection and IoC Containers?
- Dependency Injection and Singleton. Are they two entirely different concepts?
- Dependency injection: How to sell it
- Difference between Dependency Injection (DI) and Inversion of Control (IOC)
- Dependency injection: what belongs in the constructor?
- S.O.L.I.D., avoiding anemic domains, dependency injection?
- Static methods vs singletons: choose neither
3