How is URL delivered to the router in Cake?

126 Views Asked by At

www.foo.com/blog/posts/view/12/12/2013

There is no possible file corresponds to this request. So this URL needs to be parsed by some logic, or else you get a 404.

Since there is no corresponding file, the response cannot be automated by the server. I was just wondering which part of Cake FIRST responds to a request like this. I understand simple page requests are first parsed and resolved by the router. But the URL cannot just magically get to the front door of the router, right? I really want to know what is going on behind the scene that brings the URL to the router.

1

There are 1 best solutions below

0
On BEST ANSWER

Check your app/webroot/index.php, the bottom:

$Dispatcher = new Dispatcher();
$Dispatcher->dispatch(
    new CakeRequest(),
    new CakeResponse()
);

The key method of the Dispatcher is parseParams. This method gets triggered through the event system at the start of Dispatcher::dispatch(), checkt that method as well in the class.

What happens is basically that the dispatcher uses the router to parse the plain url and turns it into params and adds the parsed result to the request object and then dispatches a controller based on the parsed result.

/**
 * Applies Routing and additionalParameters to the request to be dispatched.
 * If Routes have not been loaded they will be loaded, and app/Config/routes.php will be run.
 *
 * @param CakeEvent $event containing the request, response and additional params
 * @return void
 */
        public function parseParams($event) {
                $request = $event->data['request'];
                Router::setRequestInfo($request);
                $params = Router::parse($request->url);
                $request->addParams($params);

                if (!empty($event->data['additionalParams'])) {
                        $request->addParams($event->data['additionalParams']);
                }
        }