简单的mvc框架
1.建立入口文件public/index.php
代码不用解释,就是new个类接下来去继续处理,TZD_ENV定义下环境,可灵活决定错误提示级别。
<?php
defined('TZD_ENV') or define('TZD_ENV', 'dev');
define("ROOT_PATH", str_replace("\\", "/", dirname(__DIR__)) . "/");
require(ROOT_PATH . '/core/Application.php');
$application = new \core\Application();
$application->start();
2.建立Application文件core/Application.php
代码如下,读取配置信息、定义常量、解析路由、注册自动加载函数。
主要这个spl_autoload_register函数作用了解下
<?php
namespace core;
class Application
{
public function __construct()
{
if (TZD_ENV == "prod") {
error_reporting(E_ERROR);
}
}
/**
* 执行路由
*/
private static function getDispatch()
{
$controller = "\\" . P . "\\controller\\" . C . "Controller";
$action = A;
$object = new $controller;
$object->$action();
}
/**
* 解析路由,public/index.php?r=admin/student/student
*/
private static function getRoute()
{
$route = $_REQUEST["r"];
$route = explode('/', $route);
define("P", $route[0] ?? "home");
define("C", ucfirst($route[1]) ?? "Index");
define("A", $route[2] ?? "index");
}
/**
* 自动加载
*/
private static function getAutoLoad()
{
spl_autoload_register([__CLASS__, "setAutoLoadFile"]);
}
private static function setAutoLoadFile($class)
{
$class = basename($class);
$class = str_replace('\\', '/', $class);
$coreFile = ROOT_PATH . $class . ".php";
if (file_exists($coreFile)) {
include $coreFile;
}
$controllerFile = APP_PATH . $class . ".php";
if (file_exists($controllerFile)) {
include $controllerFile;
}
$modelFile = APP_PATH . P . "/model/" . $class . ".php";
if (file_exists($modelFile)) {
include "$modelFile";
}
$vendorFile = VENDOR_PATH . $class . ".php";
if (file_exists($vendorFile)) {
include $vendorFile;
}
}
public static function start()
{
global $config;
$config = include ROOT_PATH . "/config/database.php";
define("CORE_PATH", ROOT_PATH . "core/");
define("APP_PATH", ROOT_PATH . "app/");
define("CONFIG_PATH", ROOT_PATH . "config/");
define("VENDOR_PATH", ROOT_PATH . "vendor/");
define("RESOURCES_PATH", ROOT_PATH . "resources/");
self::getRoute();
self::getAutoLoad();
self::getDispatch();
}
}
3.下面写控制器的父类,加入smarty模版引擎core/Controller.php
<?php
namespace core;
class Controller{
protected $smarty;
public function __construct(){
include VENDOR_PATH . "smarty/Smarty.class.php";
$this->smarty = new \Smarty();
$this->smarty->template_dir = APP_PATH . P . "/view/";
$this->smarty->compile_dir = RESOURCES_PATH . "views";
}
protected function assign($name, $value = ""){
$this->smarty->assign($name, $value);
}
protected function display($template = ""){
try {
$this->smarty->display($template);
}
catch (\SmartyException | \Exception $e){
echo $e->getMessage();
}
}
}
4.接着继续写数据库类core/database.php
<?php
namespace core;
use PDO;
use PDOException;
class Database{
protected $pdo;
public function __construct($databaseInfo = array()){
$type = $databaseInfo["type"] ?? "mysql";
$host = $databaseInfo["host"] ?? "localhost";
$port = $databaseInfo["port"] ?? "3306";
$user = $databaseInfo["user"] ?? "root";
$password = $databaseInfo["password"] ?? "";
$dbName = $databaseInfo["dbName"] ?? "";
$charset = $databaseInfo["charset"] ?? "utf8";
try{
$dsn = $type . ":host=" . $host . ";port=" . $port . ";dbname=" . $dbName . ";charset=" . $charset;
$this->pdo = new PDO($dsn, $user, $password);
}
catch (PDOException $e){
echo "数据库连接失败!<br/>";
echo "错误文件为:" . $e->getFile() . "<br/>";
echo "错误行号为:" . $e->getLine() . "<br/>";
echo "错误描述为:" . $e->getMessage();
exit;
}
}
public function daoQuery($sql): array{
try{
$stmt = $this->pdo->query($sql);
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
catch (PDOException $e){
$this->dataException(e);
}
}
public function daoExec($sql){
try{
return $this->pdo->exec($sql);
}
catch (PDOException $e){
$this->dataException($e);
}
}
private function dataException($e){
echo "SQL执行错误!<br/>";
echo "错误文件为:" . $e->getFile() . "<br/>";
echo "错误行号为:" . $e->getLine() . "<br/>";
echo "错误描述为:" . $e->getMessage();
exit;
}
}
5.接着写模型父类core/model.php
<?php
namespace core;
class Model{
protected $dao;
protected $tableName;
protected $fields;
public function __construct(){
global $config;
$this->dao = new Database($config["database"]);
$this->getFields();
}
protected function getFields(){
$sql = "DESC {$this->tableName}";
$rows = $this->query($sql);
foreach($rows as $row){
$this->fields[] = $row["Field"];
if($row["Key"] == "PRI"){
$this->fields["Key"] = $row["Field"];
}
}
}
protected function query($sql): array{
return $this->dao->daoQuery($sql);
}
protected function exec($sql){
return $this->dao->daoExec($sql);
}
public function autoInsert($data){
$keys = $values = "";
foreach($this->fields as $k => $v) {
if($k == "Key")
continue;
if(array_key_exists($v, $data)){
$keys .= $v . ",";
$values .= "'" . $data[$v] . "'.";
}
}
$keys = rtrim($keys, ",");
$values = rtrim($values, ",");
$sql = "insert into{$this->tableName}({$keys}) values({$values})";
return $this->exec($sql);
}
public function deleteById($id){
if(!isset($this->fields["Key"])){
return false;
}
$sql = "delete from {$this->tableName} where {$this->fields["Key"]} = '{$id}'";
return $this->exec($sql);
}
public function autoUpdate($id, $data){
$where = " where {$this->fields['Key']} = '{$id}'";
$sql = "update {$this->tableName} set";
foreach ($data as $Key => $value){
$sql .= $Key . "='" . $value . "',";
}
$sql = rtrim($sql, ",") . $where;
return $this->exec($sql);
}
public function getById($id){
if(!isset($this->fields["Key"])){
return false;
}
$sql = "select * from {$this->tableName} where {$this->fields['Key']} = '{$id}'";
return $this->query($sql);
}
}
6.配置数据库文件core/database.php
<?php
return array(
"database" => array(
"type" => "mysql",
"host" => "localhost",
"port" => "3306",
"user" => "root",
"password" => "it1995",
"charset" => "utf8",
"dbName" => "TZD215",
)
);
?>
项目目录如下
然后就可以在app目录下建自己的应用了,比如admin/controller/IndexController.php的index方法,访问路径public/index.php?r=admin/index/index就ok了~~
项目地址:待发布github,发布后会更新!