MVC(Model-View-Controller)是一种软件架构模式,常用于Web应用程序的开发,主要用于将应用程序的数据、用户界面和控制逻辑分离开来,以提高应用程序的可维护性和可扩展性。
下面是一些编写PHP MVC框架的步骤:.
1. 定义核心文件和目录
包括控制器、视图、模型、路由、数据库等核心功能的文件和目录结构。例如:
- controllers/
- models/
- views/
- core/
2. 创建路由
路由是应用程序的核心,用于将URL映射到控制器和动作。一般而言,路由需要解析URL并提取控制器和动作名称,然后调用相应的控制器和方法。例如:
// routes.php
$routes = [
'/' => 'HomeController@index',
'/user' => 'UserController@index',
'/user/create' => 'UserController@create',
'/user/store' => 'UserController@store',
'/user/edit/{id}' => 'UserController@edit',
'/user/update/{id}' => 'UserController@update',
'/user/delete/{id}' => 'UserController@delete',
];
3. 创建控制器
控制器是应用程序的逻辑处理层,负责处理请求并返回响应。它接收从路由解析过来的参数,并调用相应的模型和视图来处理请求。例如:
// controllers/UserController.php
class UserController {
public function index() {
$users = UserModel::all();
View::render('users/index', $users);
}
public function create() {
View::render('users/create');
}
public function store() {
$user = new UserModel($_POST);
$user->save();
redirectTo('/user');
}
public function edit($id) {
$user = UserModel::getById($id);
View::render('users/edit', $user);
}
public function update($id) {
$user = UserModel::getById($id);
$user->fill($_POST);
$user->save();
redirectTo('/user');
}
public function delete($id) {
$user = UserModel::getById($id);
$user->delete();
redirectTo('/user');
}
}
4. 创建模型
模型是应用程序的数据层,它处理数据的存储和检索。模型通常与数据库交互,负责读取、更新和删除数据。例如:
// models/UserModel.php
class UserModel {
public static function all() {
$result = DB::query('SELECT * FROM users');
return $result;
}
public static function getById($id) {
$result = DB::query('SELECT * FROM users WHERE id = ?', [$id]);
return $result[0];
}
public function fill($data) {
$this->name = $data['name'];
$this->email = $data['email'];
$this->password = $data['password'];
}
public function save() {
if ($this->id) {
// update user
DB::execute('UPDATE users SET name = ?, email = ?, password = ? WHERE id = ?', [
$this->name, $this->email, $this->password, $this->id
]);
} else {
// create user
DB::execute('INSERT INTO users (name, email, password) VALUES (?, ?, ?)', [
$this->name, $this->email, $this->password
]);
}
}
public function delete() {
DB::execute('DELETE FROM users WHERE id = ?', [$this->id]);
}
}
5. 创建视图
视图是应用程序的用户界面层,它负责显示用户界面。视图通常使用模版引擎来渲染HTML、CSS和JavaScript等内容。例如:
<!-- views/users/index.php -->
<h1>Users List</h1>
<table>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php foreach ($users as $user): ?>
<tr>
<td><?php echo $user['name']; ?></td>
<td><?php echo $user['email']; ?></td>
<td>
<a href="/user/edit/<?php echo $user['id']; ?>">Edit</a>
<a href="/user/delete/<?php echo $user['id']; ?>">Delete</a>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
6. 创建核心功能
核心功能包括路由、模版引擎、数据库、HTTP请求和响应等功能。例如:
// core/Router.php
class Router {
private static $routes = [];
public static function addRoute($uri, $handler) {
self::$routes[$uri] = $handler;
}
public static function dispatch($uri) {
if (isset(self::$routes[$uri])) {
$handler = self::$routes[$uri];
list($controller, $action) = explode('@', $handler);
$controller = 'controllers\\' . $controller;
$controller = new $controller;
$controller->$action();
} else {
http_response_code(404);
echo "404 Not Found";
}
}
}
// core/DB.php
class DB {
private static $conn = null;
public static function connect() {
if (self::$conn === null) {
self::$conn = new PDO('mysql:host=localhost;dbname=myapp', 'root', '');
}
}
public static function query($sql, $params = []) {
self::connect();
$stmt = self::$conn->prepare($sql);
$stmt->execute($params);
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $result;
}
public static function execute($sql, $params = []) {
self::connect();
$stmt = self::$conn->prepare($sql);
$stmt->execute($params);
}
}
// core/View.php
class View {
public static function render($view, $data = []) {
extract($data);
include "views/$view.php";
}
}
// core/Helpers.php
function redirectTo($uri) {
header("Location: $uri");
}
7. 部署应用程序
将所有文件和目录上传到服务器,并在服务器上安装和配置必要的软件(如PHP和MySQL)。配置Web服务器(如Apache或Nginx)以使用.htaccess文件来重定向所有请求到index.php文件。例如:
# .htaccess
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)$ index.php [QSA,L]
这样,当用户访问应用程序的URL时,请求将进入index.php文件,然后通过路由转发到相应的控制器和动作。最后,控制器将调用相应的模型和视图来处理请求,并返回响应。