Skip to content

Instantly share code, notes, and snippets.

@kieraneglin
Last active February 20, 2018 20:18
Show Gist options
  • Save kieraneglin/8e24c3e008bd4f0504124c2d76c1d1ac to your computer and use it in GitHub Desktop.
Save kieraneglin/8e24c3e008bd4f0504124c2d76c1d1ac to your computer and use it in GitHub Desktop.
PHP Router Syntax Example
<?php
$router = new Router();
// Traditional routes
$router->route('POST', '/posts', 'posts#create'); // This looks for PostsController with a method named `create`
$router->route('GET', '/posts', 'posts#index');
$router->route('GET', '/posts/{:id}', 'posts#show'); // This will pass a param with a key of `id` and a value of whatever is in the URL
$router->route('PATCH', '/posts/{:id}', 'posts#update');
$router->route('GET', '/me', 'users#show'); // It's worth noting that the lack of a trailing slash is important. `/me/` will not match `/me` and vice-versa
// Shorthand (Available for GET, POST, PATCH, PUTS, and DELETE)
$router->post('/posts', 'posts#create');
$router->get('/posts', 'posts#index');
$router->patch('/posts/{:id}', 'posts#update');
// Namespaced controllers
$router->route('GET', '/admin/settings', 'admin/settings#index');
// Catch-all route
$router->route('GET', '{:all}', 'pages#not_found');
$router->execute($_SERVER);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment