模仿 ThinkPHP - db 类的封装实例

模仿 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($tbl)
    {
        $this-
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值