Link to other classes in the class - php

Let's say I have two php classes - class Security

and classDatabase

Safety

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 to achieve this, but I'm not sure about the best practice.

Is it better to instantiate both types:

$db = new Database;
$sec = new Security($db);

      

and then in the Security class, use a constructor to pass the db instance to it?

Or would you create a new instance in the __constructor method in the security class?

Any best practice would be grateful.

+3


source to share


1 answer


Instantiate both and then in the security class use the constructor to pass the db instance to it



The approach you signed up is called Dependency Injection and is generally the best solution for your case from an architectural point of view.

+2


source







All Articles