When designing PHP classes, what strategies can be employed to split responsibilities and ensure proper initialization of objects?
When designing PHP classes, one strategy to split responsibilities and ensure proper initialization of objects is to use constructor injection. This means passing dependencies into the class constructor rather than creating them inside the class. This promotes loose coupling and allows for easier testing and maintenance of the code.
class Database {
private $connection;
public function __construct(PDO $connection) {
$this->connection = $connection;
}
// other methods that use $this->connection
}
$pdo = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
$database = new Database($pdo);
Related questions
-
MVC pattern AJAX jQuery
-
PHPMailer localhost SMTP
-
PHP function retrieve