模仿 ThinkPHP - db 类的封装实例:
class Db extends \mysqli
{
// 实例对象
protected static $_instance = null;
// mysql配置
protected static $options = [
// 服务器地址
'host' => '127.0.0.1',
// 数据库名
'database' => 'test',
// 用户名
'username' => 'root',
// 密码
'password' => 'root',
// 端口
'hostport' => '3306',
// socket
"socket" => "",
// 数据库编码默认采用utf8
'charset' => 'utf8mb4',
// 数据库表前缀
'prefix' => 'fd_',
];
// 表
protected $tbl = null;
// 条件
protected $where = "";
// 字段,field 被占有
protected $f = "*";
// 排序
protected $order = "";
// 分页
protected $limit = "";
// 关联
protected $join = "";
// $lastSql
protected $lastSql = "";
/**
* Db constructor.
* @param string $host
* @param string $username
* @param string $passwd
* @param string $dbname
* @param int $port
* @param string $socket
* @author atong
*/
public function __construct(string $host, string $username, string $passwd, string $dbname, int $port, string $socket)
{
@parent::__construct($host, $username, $passwd, $dbname, $port, $socket);
if ($this->connect_errno) {
exit("mysql连接错误[{$this->connect_errno}]:{$this->connect_error}");
}
$this->set_charset(self::$options["charset"]);
}
/**
* 数据库初始化,并取得数据库类实例
* @access public
* @param array $options 连接配置
* @param bool $is_force 连接标识 true 强制重新连接
* @author atong
* @return Mysql
*/
public static function getInstance($options = [])
{
if (self::$_instance == null) {
$db_config = self::$options;
self::$_instance = new self(
$options["host"] ?? $db_config["host"]
, $options["username"] ?? $db_config["username"]
, $options["password"] ?? $db_config["password"]
, $options["database"] ?? $db_config["database"]
, $options["hostport"] ?? $db_config["hostport"]
, $options["socket"] ?? $db_config["socket"]
);
}
return self::$_instance;
}
/**
* todo::链式函数封装
* 模仿 tp db类的风格
*/
// 无前缀
public function _table($