1.2 connect to mysql
PHP
的项目怎么少得了数据库的连接呢,接下来实现数据库的连接
创建配置
Step1
:在根目录创建config
文件夹用于存放配置文件(项目中会有许多不同的配置,关于数据库,缓存,日志,路由等等,所以需要一个专门存放配置文件的地方,并拆分成不同的配置文件),主配置文件命名为config.php
,其余配置文件在主配置文件中进行聚合。此处共在config
文件夹下创建两个文件:config.php
和db.php
,其内容分别如下:
// config.php
<?php
return [
'config_files' => 'db',
];
--snip--
// db.php
<?php
return [
'db_type' => 'mysql',
'db_host' => '127.0.0.1',
'db_name' => 'start_php_framework',
'db_user' => 'root',
'db_passwd' => 'root',
'db_port' => '3306',
'db_charset' => 'utf8mb4',
];
读取配置
Step2
:在根目录创建core
文件夹,用于存放框架的核心源码,包括:配置加载,数据库连接,缓存连接,路由实现,日志记录等基础源码。此处我们先创建一个Config.php
用于读取配置文件的信息,Config.php
内容如下:
<?php
namespace core;
class Config
{
// 存放配置信息的数组
public $config = [];
public $defaultConfig;
public function __construct()
{
$this->defaultConfig = require '../config/config.php';
$this->loadConfigFiles();
}
public function getConfig()
{
return $this->config;
}
/**
* 加载配置文件
*/
private function loadConfigFiles()
{
$this->config = $this->defaultConfig;
// 其余配置文件非空,一起加载进来
if ($this->defaultConfig['config_files'] != '') {
$configFiles = explode(',', $this->defaultConfig['config_files']);
foreach ($configFiles as $kCfg => $vCfg) {
$this->config = array_merge($this->config, require '../config/' . $vCfg . '.php');
}
}
}
}
引入composer
- 这里已经使用了命名空间,所以我们引入
composer
进行命名空间的简单管理。在项目的根目录创建composer.json
,其内容如下:
{
"name": "zhusc/start_php_framework",
"description": "try to build php framework",
"type": "project",
"keywords": [
"php",
"start"
],
"homepage": "https://read.likefirework.com/",
"license": "Apache-2.0",
"authors": [
{
"name": "zhusc",
"email": "510644654@qq.com"
}
],
"require": {
"php": ">=7.2.1"
},
"autoload": {
"psr-4": {
"core\\": "core"
}
}
}
- 注意其中的
autoload -> psr-4
,任意项目都可以在这边定义自己的命名空间,冒号左侧为命名空间的名字,右侧为相对应的文件夹。创建了composer.json
之后在cmd
中进入项目的根目录,运行composer install
,会自动在根目录下生成vendor
,待后续使用。。
创建应用启动文件
Step3
:再在core
文件夹下创建App.php
,这是启动整个应用的关键,我们当下先在其中实现配置的加载和数据库的连接。App.php
内容如下:
<?php
namespace core;
use core\Config;
class App
{
static $cfg;
/**
* 框架运行入口
*/
public static function run()
{
// 装载配置文件
$config = new Config();
self::$cfg = $config->getConfig();
$return = [
'config' => self::$cfg,
];
return $return;
}
}
使用启动文件
Step4
:修改项目入口index.php
,尝试运行项目,修改后的index.php
内容为:
<?php
// composer自动加载
require_once '../vendor/autoload.php';
// App
require_once '../core/App.php';
$res = \core\App::run();
echo '<pre>';
var_dump($res);
Step5
:此时刷新浏览器,输出的内容为:
array(1) {
["config"]=>
array(8) {
["config_files"]=>
string(2) "db"
["db_type"]=>
string(5) "mysql"
["db_host"]=>
string(9) "127.0.0.1"
["db_name"]=>
string(9) "start_php_framework"
["db_user"]=>
string(4) "root"
["db_passwd"]=>
string(9) "root"
["db_port"]=>
string(4) "3306"
["db_charset"]=>
string(7) "utf8mb4"
}
}
Step6
:到上一步为止,配置已经读取成功,接下来是建立数据库的连接。我们在core
文件夹下创建一个db
文件夹,用于实现不同的数据库连接,此处我们以MySQL
为例,在core/db
下新建Mysql.php
,其内容如下:
<?php
namespace core\db;
class Mysql
{
private $cfg;
public function __construct($host, $user, $passwd, $dbname)
{
$con = mysqli_connect($host, $user, $passwd, $dbname);
// 检查连接
if (!$con) {
die("连接错误: " . mysqli_connect_error());
} else {
return $con;
}
}
}
Step7
:修改App.php
的内容,上一步我们只是读取了配置,现在尝试进行数据库的连接,修改后的内容如下:
<?php
namespace core;
use core\Config;
use core\db\Mysql;
class App
{
static $cfg;
/**
* 框架运行入口
*/
public static function run()
{
// 装载配置文件
$config = new Config();
self::$cfg = $config->getConfig();
if (strtolower(self::$cfg['db_type']) == 'mysql') {
$dbCon = new Mysql(self::$cfg['db_host'], self::$cfg['db_user'], self::$cfg['db_passwd'], self::$cfg['db_name']);
}
$return = [
'config' => self::$cfg,
'dbCon' => $dbCon,
];
return $return;
}
}
Step8
:再次刷新浏览器,其内容已经变成了:
array(2) {
["config"]=>
array(8) {
["config_files"]=>
string(2) "db"
["db_type"]=>
string(5) "mysql"
["db_host"]=>
string(9) "127.0.0.1"
["db_name"]=>
string(9) "start_php_framework"
["db_user"]=>
string(4) "root"
["db_passwd"]=>
string(9) "root"
["db_port"]=>
string(4) "3306"
["db_charset"]=>
string(7) "utf8mb4"
}
["dbCon"]=>
object(core\db\Mysql)#5 (1) {
["cfg":"core\db\Mysql":private]=>
NULL
}
}
- 至此,数据库的连接已经成功,我们这一步实现了:配置文件的设置和读取、命名空间、MySQL的连接,并在入口文件引用
App.php
以启动应用,框架的大体结构已经隐约可见了。
项目结构
此时的项目目录结构:
start_php_framework [框架根目录]
├─ config [配置文件目录]
│ ├─ config.php [主配置文件]
│ └─ db.php [数据库配置文件]
├─ core [框架核心源码目录]
│ ├─ db [各类数据库驱动文件存储目录]
│ │ └─ Mysql.php [MySQL连接驱动]
│ ├─ App.php [应用启动文件]
│ └─ Config.php [读取配置文件]
├─ vendor [composer自有文件夹,将来存储第三方扩展]
│ ├─ composer [composer自有文件夹]
│ └─ autoload.php [自动加载关键文件,一定要在入口文件引用,且在App.php之前]
├─ web [框架入口]
│ └─ index.php [框架入口文件]
└─ composer.json [composer描述文件]