Skip to content

Instantly share code, notes, and snippets.

@magussiro
Forked from jaceju/example.php
Created July 17, 2020 15:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save magussiro/e817f296f586f6f66ed55707c62f1d75 to your computer and use it in GitHub Desktop.
Save magussiro/e817f296f586f6f66ed55707c62f1d75 to your computer and use it in GitHub Desktop.
物件導向基礎與物件導向設計入門
<?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' => 'john@example.com',
]);
$user1->save();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment