在PHP中,MVC(Model-View-Controller)是一种常用的设计模式,用于将应用程序的业务逻辑、数据模型和用户界面分离。以下是一个简单的PHP MVC框架项目实例分析:
my_mvc_project/
├── app/
│ ├── Controller/
│ │ └── HomeController.php
│ ├── Model/
│ │ └── User.php
│ ├── View/
│ │ └── Home.php
│ └── bootstrap.php
├── public/
│ └── index.php
└── vendor/
public/index.php
)<?php
require __DIR__ . '/../vendor/autoload.php';
use App\Controller\HomeController;
$controller = new HomeController();
$controller->index();
vendor/autoload.php
)通常使用Composer来管理依赖库,并生成自动加载文件。假设你有一个composer.json
文件:
{
"require": {}
}
运行composer install
后,vendor/autoload.php
会自动加载所有依赖。
app/Controller/HomeController.php
)<?php
namespace App\Controller;
use App\Model\User;
use App\View\Home;
class HomeController {
public function index() {
$user = new User();
$user->setName('John Doe');
$user->setEmail('john@example.com');
$view = new Home();
$view->setData(['user' => $user]);
$view->render();
}
}
app/Model/User.php
)<?php
namespace App\Model;
class User {
private $name;
private $email;
public function setName($name) {
$this->name = $name;
}
public function setEmail($email) {
$this->email = $email;
}
public function getName() {
return $this->name;
}
public function getEmail() {
return $this->email;
}
}
app/View/Home.php
)<?php
namespace App\View;
class Home {
private $data;
public function setData($data) {
$this->data = $data;
}
public function render() {
echo '<h1>Welcome, ' . htmlspecialchars($this->data['user']->getName()) . '</h1>';
echo '<p>Email: ' . htmlspecialchars($this->data['user']->getEmail()) . '</p>';
}
}
app/bootstrap.php
)<?php
require __DIR__ . '/../vendor/autoload.php';
use App\Controller\HomeController;
$controller = new HomeController();
$controller->index();
这个简单的PHP MVC框架实例展示了如何将应用程序的业务逻辑、数据模型和用户界面分离。通过这种设计模式,代码更加模块化,易于维护和扩展。