Say I have two php classes - class Security and class Database
Security
class Security {
public function userPermissions() {
//use getData() from Database to obtain information
}
}
Database
class Database {
public function getData() {
// some code
}
}
The security class needs to get data using the database class, there are many ways of achieving this but am not sure of best practice.
Is it better to do create an instance of both like;
$db = new Database;
$sec = new Security($db);
and then in the Security class use a constructor to pass the instance of the db to it?
Or would you create a new instance in the __constructor method within the security class?
I'd be grateful for any best practice.
Create an instance of both and then in the Security class use a constructor to pass the instance of the db to it
The approach you described is called Dependency injection and it is generally better solution for your case from the architectural point of view.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With