Front controller pattern - is router a front contr

2019-05-04 19:13发布

问题:

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");
}