Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Referencing other classes in a class - php

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.

like image 517
Simon R Avatar asked Nov 27 '25 04:11

Simon R


1 Answers

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.

like image 193
zavg Avatar answered Nov 28 '25 16:11

zavg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!