What are some common issues with using singletons in PHP and how can dependency injection help alleviate these issues?
Issue: Singletons in PHP can lead to tight coupling and make code difficult to test and maintain. Dependency injection can help alleviate these issues by allowing objects to be passed as dependencies rather than relying on a global instance. Example PHP code snippet implementing dependency injection:
class Database {
private $connection;
public function __construct($connection) {
$this->connection = $connection;
}
// Database methods here
}
class UserRepository {
private $database;
public function __construct(Database $database) {
$this->database = $database;
}
// UserRepository methods here
}
$pdo = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
$database = new Database($pdo);
$userRepository = new UserRepository($database);