에게 매우 일반적인 패턴이다 (OOP + 데이터베이스 기반 웹 사이트에 대한 다른 팁도 감사합니다)).
데이터베이스 개체를 단일 개체로 만드는 목적은 페이지로드 당 하나의 연결 만 수행되도록하는 것입니다. 어떤 이유로 여러 연결이 필요한 경우 다른 방법으로 연결하는 것이 좋습니다. 관련없는 클래스 내에 데이터베이스 객체를 생성하는 대신 생성자를 통해 전달하는 것이 중요하므로 코드를보다 쉽게 테스트하고 디버깅 할 수 있습니다.
// Basic singleton pattern for DB class
class DB
{
// Connection is a static property
private static $connection;
// Constructor is a private method so the class can't be directly instantiated with `new`
private function __construct() {}
// A private connect() method connects to your database and returns the connection object/resource
private static function connect() {
// use PDO, or MySQLi
$conn = new mysqli(...);
// Error checking, etc
return $conn;
}
// Static method retrieves existing connection or creates a new one if it doesn't exist
// via the connect() method
public static function get_connection() {
if (!self::$connection) {
self::$connection = self::connect();
// This could even call new mysqli() or new PDO() directly and skip the connect() method
// self::$connection = new mysqli(...);
}
return self::$connection;
}
}
class Other_Class
{
// accepts a DB in constructor
public function __construct($database) {
//stuff
}
}
// Database is created by calling the static method get_connetion()
$db = DB::get_connection();
$otherclass = new Other_Class($db);
// Later, to retrieve the connection again, if you don't use the variable $db
// calling DB::get_connection() returns the same connection as before since it already exists
$otherclass2 = new Other_Class(DB::get_connection());
또 다른 방법은 직접 중 하나 mysqli
또는 PDO
확장 데이터베이스 클래스 를 만드는 것입니다. 이 경우, __construct()
방법은
public static function get_connection() {
if (!self::$connection) {
self::$connection = new self(/* params to constructor */);
}
return self::$connection;
}
CakePHP의 ORM 기능을 사용하면 명백한 이유가 없으므로 여분의 오버 헤드가 발생하지 않으므로 추가 기능이 정말 마음에 들지 않았습니다. 독립 실행 형 ORM이이를 어떻게 처리합니까? –
그들은 어떻게 처리합니까? 죄송 합니다만 질문이 없습니다. –