-
-
Save magussiro/e817f296f586f6f66ed55707c62f1d75 to your computer and use it in GitHub Desktop.
物件導向基礎與物件導向設計入門
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
abstract class Database | |
{ | |
public function __construct() | |
{ | |
$this->connect(); | |
} | |
abstract public function connect(); | |
/** | |
* @param $sql | |
* @param $values | |
* @return mixed | |
*/ | |
abstract public function query($sql, $values); | |
public function quoteIdentifier($col) | |
{ | |
return $col; | |
} | |
public function insert($table, array $bind) | |
{ | |
$cols = []; | |
$vals = []; | |
foreach ($bind as $col => $val) { | |
$cols[] = $this->quoteIdentifier($col); | |
$vals[] = '?'; | |
} | |
$sql = "INSERT INTO " | |
. $this->quoteIdentifier($table) | |
. ' (' . implode(', ', $cols) . ') ' | |
. 'VALUES (' . implode(', ', $vals) . ')'; | |
return $this->query($sql, $bind); | |
} | |
} | |
class MysqliDriver extends Database | |
{ | |
private $conn = null; | |
public function connect() | |
{ | |
$this->conn = new mysqli('localhost', 'root', '123456', 'test'); | |
} | |
public function quoteIdentifier($col) | |
{ | |
return '`' . $col . '`'; | |
} | |
public function query($sql, $values) | |
{ | |
$binds = []; | |
$types = str_pad('', count($values), 's'); | |
$binds[] = &$types; | |
foreach ($values as $key => $value) { | |
$binds[] = &$values[$key]; | |
} | |
$stmt = $this->conn->prepare($sql); | |
call_user_func_array([$stmt, 'bind_param'], $binds); | |
$stmt->execute(); | |
$stmt->close(); | |
} | |
} | |
class Model | |
{ | |
/** | |
* @var Database | |
*/ | |
protected static $db; | |
protected $table = 'table'; | |
protected $data = []; | |
public static function setDb(Database $db) | |
{ | |
self::$db = $db; | |
} | |
public function __construct($data) | |
{ | |
$this->data = $data; | |
} | |
public function save() | |
{ | |
self::$db->insert($this->table, $this->data); | |
} | |
} | |
class User extends Model | |
{ | |
protected $table = 'users'; | |
} | |
User::setDb(new MysqliDriver()); | |
$user1 = new User([ | |
'firstname' => 'John', | |
'lastname' => 'Doe', | |
'email' => '[email protected]', | |
]); | |
$user1->save(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment