在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框架實例展示了如何將應用程序的業務邏輯、數據模型和用戶界面分離。通過這種設計模式,代碼更加模塊化,易于維護和擴展。