PHP MVC框架多控制器使用疑问及路由规则相关咨询
Hey there! Let's break down how to work with your PHP MVC framework's routing and build that dashboard you're looking to create.
First, let's recap the core routing logic you described to ensure we're aligned:
- A URL like
http://localhost/myproject/dashboard/indexwill map to:- Controller:
dashboard-controller(matching the kebab-case segment in the URL) - Method:
index()inside that controller
- Controller:
- Adding parameters (e.g.,
http://localhost/myproject/dashboard/user-stats/123/2024) will pass123and2024as arguments to theuser-statsmethod in thedashboard-controller
Here's a quick example of what that controller might look like:
// dashboard-controller.php class DashboardController { // Main dashboard landing page public function index() { // Fetch key dashboard data (we'll cover models next) $totalUsers = $this->userModel->getTotalUsers(); $recentOrders = $this->orderModel->getRecentOrders(5); // Pass data to the view template $this->render('dashboard/index', [ 'totalUsers' => $totalUsers, 'recentOrders' => $recentOrders ]); } // User stats page with parameters public function userStats($userId, $year) { $userStats = $this->statsModel->getUserYearlyStats($userId, $year); $this->render('dashboard/user-stats', ['stats' => $userStats]); } }
1. Create the Dashboard Controller
- Follow your framework's naming rules: if controllers use the
-controllersuffix, name the filedashboard-controller.php - Add methods for each dashboard section (e.g.,
indexfor the main view,salesOverviewfor sales data,userStatsfor user-specific metrics)
2. Use Models for Data Retrieval
Never put database logic directly in controllers—keep your code clean with models:
// user-model.php class UserModel { public function getTotalUsers() { // Assume $this->db is your framework's database connection $stmt = $this->db->prepare("SELECT COUNT(id) FROM users"); $stmt->execute(); return $stmt->fetchColumn(); } }
3. Build View Templates
Create a dedicated views/dashboard folder to organize your dashboard's frontend:
<!-- views/dashboard/index.php --> <div class="dashboard-wrapper"> <h1>Admin Dashboard</h1> <div class="stats-grid"> <div class="stat-card"> <h3>Total Users</h3> <p class="stat-number"><?php echo $totalUsers; ?></p> </div> <div class="stat-card"> <h3>Recent Orders</h3> <ul> <?php foreach ($recentOrders as $order): ?> <li>Order #<?php echo $order['id']; ?> - $<?php echo $order['total']; ?></li> <?php endforeach; ?> </ul> </div> </div> </div>
4. Test the Route
Once your controller, model, and view are set up, access the dashboard via:http://localhost/myproject/dashboard/index
If you need to add protected access (like requiring admin login), most MVC frameworks let you add middleware to the controller or route—for example:
// Add authentication middleware to the dashboard controller $this->middleware('auth', ['only' => ['index', 'userStats']]);
内容的提问来源于stack exchange,提问作者YJV18

