Do you mean going from a URL to a controller? The low-tech solution could look something like this:
function routingMatch($urlPath)
{
if ($urlPath == '/') {
return array('controller' => 'Blog', 'action' => 'list');
} elseif ($urlPath == '/show' && isset($_GET['id'])) {
return array('controller' => 'Blog', 'action' => 'show');
}
}
// ...
$routeParameters = routingMatch($_SERVER['REQUEST_URI']);
Or we could use the Symfony Routing component. (Beside being a full-stack framework, Symfony is also a set of standalone libraries, so we can use the routing component without using the full framework.)
// src/config/routing.php
use Symfony\\Component\\Routing\\RouteCollection;
use Symfony\\Component\\Routing\\Route;
$collection = new RouteCollection();
$collection->add('blog_list', new Route('/', array(
'controller' => 'Blog', 'action' => 'list',
)));
$collection->add('blog_show', new Route('/show/{id}', array(
'controller' => 'Blog', 'action' => 'show',
)));
return $collection;
// web/index.php
use Symfony\\Component\\Routing\\RequestContext;
use Symfony\\Component\\Routing\\Matcher\\UrlMatcher;
$routes = require __DIR__.'/../src/config/routing.php';
$context = new RequestContext('/base-url');
$matcher = new UrlMatcher($routes, $context);
$parameters = $matcher->match($_SERVER['REQUEST_URI']);
In my case, I do actually use the full-stack Symfony framework, so I can define my routes in a few ways. The first is the plain PHP way, similar to the config/routing.php shown above. Or I have the option to use YAML.
# app/config/routing.yml
blog_list:
pattern: /
defaults: { _controller: AcmeBlogBundle:Blog:list }
blog_show:
pattern: /show/{id}
defaults: { _controller: AcmeBlogBundle:Blog:show }
Or I have the option to use annotations within the controller itself.
// src/Acme/BlogBundle/Controller/BlogController.php
use Symfony\\Bundle\\FrameworkBundle\\Controller\\Controller;
use Sensio\\Bundle\\FrameworkExtraBundle\\Configuration\\Route;
class BlogController extends Controller
{
/**
* @Route("/")
*/
public function listAction()
{
// ...
}
/**
* @Route("/show/{id}")
*/
public function showAction($id)
{
// ...
}
}