मैं mysql डेटाबेस से कनेक्ट करने के लिए सिंगलटन क्लास का उपयोग करने के लिए एक सरल बनाने की कोशिश कर रहा हूं और प्रश्न पूछता हूं, कोड ठीक काम करता है और मुझे इसके साथ कोई समस्या नहीं है, लेकिन जब से मैं ओओपी में नया हूं, मैं सोच रहा हूं चाहे यह बुरा अभ्यास है या नहीं।php सिंगलटन डेटाबेस कनेक्शन, क्या यह कोड खराब अभ्यास है?
यहाँ वर्ग
class Database {
private $databaseName = 'dbname';
private $host = 'localhost';
private $user = 'user';
private $password = 'pass';
private static $instance; //store the single instance of the database
private function __construct(){
//This will load only once regardless of how many times the class is called
$connection = mysql_connect($this->host, $this->user, $this->password) or die (mysql_error());
$db = mysql_select_db($this->databaseName, $connection) or die(mysql_error());
echo 'DB initiated<br>';
}
//this function makes sure there's only 1 instance of the Database class
public static function getInstance(){
if(!self::$instance){
self::$instance = new Database();
}
return self::$instance;
}
public function connect() {
//db connection
}
public function query($query) {
//queries
$sql = mysql_query($query) or die(mysql_error());
return $sql;
}
public function numrows($query) {
//count number of rows
$sql = $this->query($query);
return mysql_num_rows($sql);
}
}
//Intantiate the class
$database = Database::getInstance();
है और मैं क्या करना होगा जब मैं कक्षा उपयोग करना चाहते हैं:
$query = "SELECT * FROM registrations";
echo $database->numrows($query);
$sql = $database->query($query);
सिंगलटन पैटर्न अक्सर डेटाबेस क्लासेस, लॉगर्स, फ्रंट कंट्रोलर या अनुरोध और प्रतिक्रिया ऑब्जेक्ट्स में लागू किया जाता है। – diEcho
मुझे इस – jere
में कोई समस्या नहीं दिखाई देती है, वहां आप वहां देख सकते हैं वहां डीबी कक्षाएं हैं। यहां तक कि कोडिनेटर जैसे ढांचे को देखने के लिए यहां देखें कि उनके डीबी वर्ग कैसे काम करते हैं। –