Created by Juan Manuel Torres / @onema / onema.io
Follow Live
$request = Request::createFromGlobals(); // Create request object
$path = $request->getPathInfo(); // Get simple path info
$class = '\SDPHP\StudyGroup01\Controller\\'// Map path to class (BAD)
. trim($path, '/');
if (class_exists($class)) { // Check that class exists
$controller = new $class(); // Create new class
$response = $controller // Call action method (BAD)
->action($request);
} else {
$html = '<html><body><h1>Page Not Found</h1></body></html>';
$response = new Response($html, Response::HTTP_NOT_FOUND);
}
if ($response) { // RAW PHP Support
$response->prepare($request); // Tweak response
$response->send(); // Send back response
}
$routes = new RouteCollection();
$routes->add(
'hello', // NAME THE ROUTE
new Route( // CREATE A NEW ROUTE OBJECT
'/hello/{lang}', // CHOOSE A PATH AND WILDCARD
array(
'lang' => false, // WILDCARD DEFAULT VALUE
'_controller' => array( // CONTROLLER OPTIONS
// @todo WHY IS THIS BAD?!
// CREATE A NEW CONTROLLER
new \SDPHP\StudyGroup02\Controller\HelloWorldController(),
'translateAction' // OBJECT METHOD TO BE CALLED
)
)
));
$request = Request::createFromGlobals();
include __DIR__ . '/../app/config/routing.php';// Include routing file
$context = new RequestContext(); // create a new context
$context->fromRequest($request); // Init request context
$matcher = new UrlMatcher($routes, $context); // Create a matcher
$parameters = $matcher->match($request->getPathInfo()); // Get parameters
list($lang, $_controller, $_route) = array_values($parameters);
$request->attributes->add(['lang' => $lang]); // Lang to request (BETTER)
try { $controller = $_controller[0]; // assign controller to var
$method = $_controller[1]; // assign method to var
$response = $controller->$method($request);// call method (BETTER) } catch (ResourceNotFoundException $e) { $response = new Response('Not Found: ' . $e->getMessage(), 404); } catch (\Exception $e) { $response = new Response('Error occurred: ' . $e->getMessage(), 500);
}
$request = Request::createFromGlobals();
include __DIR__ . '/../app/config/routing.php';
$context = new RequestContext();
$context->fromRequest($request);
$matcher = new UrlMatcher($routes, $context);
$parameters = $matcher->match($request->getPathInfo());
$request->attributes->add($parameters);
try {
$resolver = new ControllerResolver(); // New Class
$controller = $resolver->getController($request);
$arguments = $resolver->getArguments($request, $controller);
$response = call_user_func_array($controller, $arguments);
} catch (ResourceNotFoundException $e) {
$response = new Response('Not Found: ' . $e->getMessage(), 404);
} catch (\Exception $e) {
$response = new Response('An error occurred: ' . $e->getMessage(), 500);
}
/hello/{lang}
/hello/improved/{lang}
/hello/inject/two/{lang}
/test/no/controller
/test/no/method