How does using a Singleton pattern for passing a database object affect code readability and maintainability in PHP projects?
Using a Singleton pattern for passing a database object can make the code less readable and maintainable as it introduces global state and tight coupling between components. This can make it harder to test and refactor the code in the future. Instead, it's recommended to use dependency injection to pass the database object where it's needed.
class Database {
private static $instance;
public static function getInstance() {
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
private function __construct() {
// Database connection setup
}
// Other database methods
}
class UserRepository {
private $db;
public function __construct(Database $db) {
$this->db = $db;
}
// UserRepository methods using $this->db
}
// Usage
$db = Database::getInstance();
$userRepository = new UserRepository($db);
Related questions
-
PHP libraries functions
-
Regular expressions PHP code pattern matching
-
PHP include statements security concerns