Mecha CMS

Mecha CMS blog and documentation.

Class Route

Updated: Sunday, 07 August 2016

Ignite specific actions based on URL pattern match.

The URL path is relative to the root domain.

Adding Routes

Route::accept('test', function() {
    echo 'Match!';
});

The route above will echo a “Match!” text to the page if the URL is http://mecha-cms.com/2016/test

Route::accept('test/(foo|bar)', function() {});

The route above will accept both http://mecha-cms.com/2016/test/foo and http://mecha-cms.com/2016/test/bar.

WildcardAccept
(:all)Accept anything.
(:any)Accept anything except /.
(:num)Accept any number.
(foo|bar)Accept foo or bar.
Route::accept(array('foo/bar', 'baz/qux'), function() {});

The route above will accept http://mecha-cms.com/2016/foo/bar and http://mecha-cms.com/2016/baz/qux.

Extracting the URL Pattern Match

You can extract the contents of the pattern match inside the parenthesis symbol and use that for your specific purpose:

Route::accept('page/(:num)', function($offset = 1) {
    echo 'We are on page ' . $offset;
});

Route::accept('(article|page)/(:num)', function($path = "", $offset = 1) {
    echo 'Slug: ' . $path . '<br>';
    echo 'Offset: ' . $offset;
});

Don’t forget to add default value for each parameter.

Route Priority

Added since version 1.1.1.

Specify the priority parameter to reorder the route stacks. The smaller the value, the earlier the route will be prioritized to be executed. Default is 10:

Route::accept('page/(:any)/(:num)', function($slug = "", $offset = 1) { … }, 11);

Route::accept('page/(:any)', function($slug = "") {
    // I’ll be the first…
}, 5);

The code above is equal to:

Route::accept('page/(:any)', function($slug = "") {
    // I’ll be the first…
}, 5);

Route::accept('page/(:any)/(:num)', function($slug = "", $offset = 1) { … }, 11);

Route Execution

Execute all routes:

Route::accept( … );
Route::accept( … );
Route::accept( … );
Route::accept( … );
…

// Execute all!
Route::execute();

Execute Specific Route

Added since version 1.1.1.

// Execute `foo/bar/(:any)/(:num)`
Route::execute('foo/bar/(:any)/(:num)', array('baz', 4));

Inside a route …

Route::accept('foo/bar/(:any)', function($slug = "") { … });

Route::accept('foo/bar/(:any)/(:num)' function($slug = "", $offset = 1) {

    // Other stuff goes here…

    Route::execute('foo/bar/(:any)', array($slug));
});

Check Route Pattern of Current Page

Added since version 1.1.3.

if(Route::is('foo/bar')) { … }

Hook Before Route Execution

Added since version 1.1.3.

Route::over('foo/bar', function() { … });
Donation and Email Subscription