問題描述
我已經閱讀了很多關于如何以及為什么在應用程序中使用 MVC 方法的文章.我已經看到并理解了模型的例子,我已經看到并理解了視圖的例子......但我仍然對控制器有點模糊.我真的很想看到一個足夠完整的控制器示例.(如果可能,使用 PHP,但任何語言都會有所幫助)
I have been reading a lot about how and why to use an MVC approach in an application. I have seen and understand examples of a Model, I have seen and understand examples of the View.... but I am STILL kind of fuzzy on the controller. I would really love to see a thorough enough example of a controller(s). (in PHP if possible, but any language will help)
謝謝.
PS:如果我能看到一個 index.php 頁面的例子也很棒,它決定使用哪個控制器以及如何使用.
PS: It would also be great if I could see an example of an index.php page, which decides which controller to use and how.
我知道控制器的工作是什么,我只是不明白如何在 OOP 中實現這一點.
I know what the job of the controller is, I just don't really understand how to accomplish this in OOP.
推薦答案
請求示例
在你的 index.php
中加入類似的內容:
Put something like this in your index.php
:
<?php
// Holds data like $baseUrl etc.
include 'config.php';
$requestUrl = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
$requestString = substr($requestUrl, strlen($baseUrl));
$urlParams = explode('/', $requestString);
// TODO: Consider security (see comments)
$controllerName = ucfirst(array_shift($urlParams)).'Controller';
$actionName = strtolower(array_shift($urlParams)).'Action';
// Here you should probably gather the rest as params
// Call the action
$controller = new $controllerName;
$controller->$actionName();
非常基礎,但你明白了......(我也沒有負責加載控制器類,但我想這可以通過自動加載來完成,或者你知道如何去做.)
Really basic, but you get the idea... (I also didn't take care of loading the controller class, but I guess that can be done either via autoloading or you know how to do it.)
簡單的控制器示例(controllers/login.php):
Simple controller example (controllers/login.php):
<?php
class LoginController
{
function loginAction()
{
$username = $this->request->get('username');
$password = $this->request->get('password');
$this->loadModel('users');
if ($this->users->validate($username, $password))
{
$userData = $this->users->fetch($username);
AuthStorage::save($username, $userData);
$this->redirect('secret_area');
}
else
{
$this->view->message = 'Invalid login';
$this->view->render('error');
}
}
function logoutAction()
{
if (AuthStorage::logged())
{
AuthStorage::remove();
$this->redirect('index');
}
else
{
$this->view->message = 'You are not logged in.';
$this->view->render('error');
}
}
}
如您所見,控制器負責應用程序的流程"——即所謂的應用程序邏輯.它不關心數據存儲和呈現.而是收集所有必要的數據(取決于當前請求)并將其分配給視圖...
As you see, the controller takes care of the "flow" of the application - the so-called application logic. It does not take care about data storage and presentation. It rather gathers all the necessary data (depending on the current request) and assigns it to the view...
請注意,這不適用于我知道的任何框架,但我相信您知道這些函數應該做什么.
Note that this would not work with any framework I know, but I'm sure you know what the functions are supposed to do.
這篇關于MVC 控制器的示例的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!