1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
| <?php
class PDOProvider {
// pattern design
protected static $instance;
private function __construct() {}
private function __clone() {}
public static function getInstance ($db,$user,$password) {
if ( ! isset ( self::$instance ) )
try {
self::$instance = new PDO ( 'mysql:host=localhost;dbname='.$db,$user,$password);
} catch (Exception $e) {
echo $e->getMessage();
}
return self::$instance;
}
}
class ClassManager {
protected static $instance;
protected $db;
public function __construct () {
// get PDO instance
$this->db = PDOProvider::getInstance('table','root','');
}
public static function getInstance () {
// return instance if doesn't exists
if ( ! isset ( $instance ) )
self::$instance = new self;
return self::$instance;
}
public function test ($value) {
if ( is_int ( $value ) )
$sql = 'SELECT COUNT(*) FROM test WHERE id='.(int)$value;
else
$sql = 'SELECT COUNT(*) FROM test WHERE name="'.$value.'"';
$req = $this->db->query($sql);
}
}
class Class extends ClassManager {
protected $manager; // instance of ClassManager
// construct function
public function __construct() {
// instance of SimManager
$this->manager = SimManager::getInstance();
}
public function __get($attr) {}
}
$test = new Class();
$test->test('value'); |
Partager