12
There are a couple of ways of doing that. Global variables is certainly one way and the most looked down upon too. You can create a Singleton and all other classes that need database access would call upon this singleton.
有幾種方法可以做到這一點。全局變量當然是一種方式,也是最容易被忽視的方式。您可以創建一個Singleton,所有其他需要數據庫訪問的類都會調用此單例。
final class Database {
private static $connection;
public static function getInstance() {
if(self::$connection == NULL) {
self::$connection = // init your database connection
}
return self::$connection;
}
}
And use this database connection object in whatever class needs it.
並且在任何類需要它時使用此數據庫連接對象。
class Application {
public function displayVar() {
echo 'hello world';
}
public function getVar() {
$db = Database::getInstance();
$sql = foo;
$db->query($sql);
}
}
This is all well for a start and a great step beyond using global variables, but you can do better with Dependency Injection. Dependency Injection is a simple concept that if a class has any external dependencies, such as the database connection in your example, you explicitly pass those to the needy class in its constructor or a method. So the new code would look something like Jonathan's solution. A major advantage of using dependency injection is in unit testing, where you can easily replace this actual database object with a mock object and pass it to whoever needs it.
除了使用全局變量之外,這一切都很好,但是你可以使用依賴注入做得更好。依賴注入是一個簡單的概念,如果一個類有任何外部依賴項,例如你的例子中的數據庫連接,你可以在它的構造函數或方法中將它們顯式傳遞給貧困類。所以新代碼看起來像Jonathan的解決方案。使用依賴注入的一個主要優點是單元測試,您可以使用模擬對象輕松替換此實際數據庫對象,並將其傳遞給任何需要它的人。
class Application {
private $db;
public function __construct(Database $db) {
$this->db = $db;
}
public function displayVar() {
echo 'hello world';
}
public function getVar() {
$sql = foo;
$this->db->query($sql);
}
}
For smaller projects, you can easily do it yourself. For large projects, there are various DI frameworks available for PHP
對於較小的項目,您可以輕松地自己完成。對於大型項目,有各種可用於PHP的DI框架