数据库连接单利模式案例

Original 2019-02-20 17:14:23 264
abstract:通过对本章的学习,通过创建Database类,实现数据库连接的单例模式。代码如下:DataBase.php<?php namespace app\index\controller; class DataBase {     //私有化构造函数     private funct

通过对本章的学习,通过创建Database类,实现数据库连接的单例模式。代码如下:

DataBase.php

<?php

namespace app\index\controller;


class DataBase
{
    //私有化构造函数
    private function  __construct()
    {
    }

    //私有化克隆函数
    private  function __clone()
    {

    }

    protected  static  $instance = null;

    //数据库连接
    private static function  iniDbArray()
    {
        $arr=[
            // 数据库类型
            'type'            => 'mysql',
            // 服务器地址
            'hostname'        => '127.0.0.1',
            // 数据库名
            'database'        => '',
            // 用户名
            'username'        => 'root',
            // 密码
            'password'        => '',
            // 端口
            'hostport'        => '',
            // 连接dsn
            'dsn'             => '',
            // 数据库连接参数
            'params'          => [],
            // 数据库编码默认采用utf8
            'charset'         => 'utf8',
            // 数据库表前缀
            'prefix'          => '',
            // 数据库调试模式
            'debug'           => true,
            // 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器)
            'deploy'          => 0
        ];
        return $arr;
    }

    //初始化
    public  static  function  getInstance()
    {
        if(static::$instance==null)
        {
            static::$instance=self::iniDbArray();
        }

        return static::$instance;
    }
}

Index.php调用:

<?php
namespace app\index\controller;

use think\Request;

class Index
{
    public function index()
    {
        dump(DataBase::getInstance());
    }

    public function hello($name = 'ThinkPHP5')
    {
        return 'hello,' . $name;
    }

    public  function  getParam(Request $request)
    {
        dump($request->param());
    }
}

效果图:

QQ截图20190220171237.jpg

Correcting teacher:韦小宝Correction time:2019-02-20 17:26:30
Teacher's summary:设计模式要多在实际的项目中去实践才能起到很大的作用 没事的时候一定要多去练习!

Release Notes

Popular Entries