abstract:通過對(duì)本章的學(xué)習(xí),通過創(chuàng)建Database類,實(shí)現(xiàn)數(shù)據(jù)庫(kù)連接的單例模式。代碼如下:DataBase.php<?php namespace app\index\controller; class DataBase { //私有化構(gòu)造函數(shù) private funct
通過對(duì)本章的學(xué)習(xí),通過創(chuàng)建Database類,實(shí)現(xiàn)數(shù)據(jù)庫(kù)連接的單例模式。代碼如下:
DataBase.php
<?php namespace app\index\controller; class DataBase { //私有化構(gòu)造函數(shù) private function __construct() { } //私有化克隆函數(shù) private function __clone() { } protected static $instance = null; //數(shù)據(jù)庫(kù)連接 private static function iniDbArray() { $arr=[ // 數(shù)據(jù)庫(kù)類型 'type' => 'mysql', // 服務(wù)器地址 'hostname' => '127.0.0.1', // 數(shù)據(jù)庫(kù)名 'database' => '', // 用戶名 'username' => 'root', // 密碼 'password' => '', // 端口 'hostport' => '', // 連接dsn 'dsn' => '', // 數(shù)據(jù)庫(kù)連接參數(shù) 'params' => [], // 數(shù)據(jù)庫(kù)編碼默認(rèn)采用utf8 'charset' => 'utf8', // 數(shù)據(jù)庫(kù)表前綴 'prefix' => '', // 數(shù)據(jù)庫(kù)調(diào)試模式 'debug' => true, // 數(shù)據(jù)庫(kù)部署方式:0 集中式(單一服務(wù)器),1 分布式(主從服務(wù)器) 'deploy' => 0 ]; return $arr; } //初始化 public static function getInstance() { if(static::$instance==null) { static::$instance=self::iniDbArray(); } return static::$instance; } }
Index.php調(diào)用:
<?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()); } }
效果圖:
Correcting teacher:韋小寶Correction time:2019-02-20 17:26:30
Teacher's summary:設(shè)計(jì)模式要多在實(shí)際的項(xiàng)目中去實(shí)踐才能起到很大的作用 沒事的時(shí)候一定要多去練習(xí)!