Front controller pattern - is router a front controller?

人盡茶涼 提交于 2019-12-07 10:54:19

问题


I'm trying to understand how a Front Controller should look like. From Wikipedia,

The Front Controller pattern is a software design pattern listed in several pattern catalogs. The pattern relates to the design of web applications. It "provides a centralized entry point for handling requests."

So, is the code below that handles routes in Slim a front controller?

$app = new \Slim\Slim();
$app->get('/books/:id', function ($id) use ($app) {

    // Get all books or one book.
    $bookModel = new ...
    $bookController = new ...

    $app->render('myTemplate.php', array('id' => $id, ...));
});

$app->run();

回答1:


provides a centralized entry point for handling requests.

Yes, Slim can be some kind of a front-controller. It handles all incoming requests and brings them to the right place/controller.

Do not confound the front-controller with the controller of a MVC pattern.

In your example the route is part of the front-controller and should call the controller of your MVC pattern. This MVC-controller (in your exmaple $bookController) is responsible for evaluating information, submitinig information to the view and display the view. So your example should look like the following:

//Inside of your frontcontroller, defining the route:
$app->get("/books/:id", "bookController:displayBook");

//Inside of your MVC bookController class:
public function displayBook($id)
{
    $book = Book::find($id);
    $app->view->set("book", $book);
    $app->view->render("form_book.php");
}


来源:https://stackoverflow.com/questions/32389438/front-controller-pattern-is-router-a-front-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!