When I’m working on a controller, I usually will combine my add/edit methods to help keep my controllers lean and mean. In the other frameworks I used this was generally as easy as adding a route like so
// CodeIgniter
$config['([a-z\_]+)/add'] = '$1/edit';
// Kohana
Route::set('manage', '<controller>/add', array(
'controller' => '[a-z0-9\_]+'
))
->defaults(array('action' => 'edit'));
// CakePHP
Router::connect('/:controller/add', array('action' => 'edit'));
However, in working with Laravel it just wasn’t that easy, probably because Laravel expects all controllers to be defined so it can do a super-quick search for them at runtime. I came up with a (hacky) solution that modified the core controller class (while I really enjoy working with Laravel the fact is its core just isn’t terribly extensible). I really hate modifying core classes.
And then – the lightbulb went on! I remembered that a) I can use anonymous functions for routing and b) Controller::call can be used anywhere.
NOTE: For now this only appears to work in subfolder controllers. It seems (from examining the generated route list) that any route that *starts* with a wildcard (eg, (:any)) will be moved to the bottom of the list. For me, this wasn’t a big deal; my add/edit classes are almost always in admin folders anyway.
Route::any('admin/(:any)/add/(:any?)', function($controller,$params=null) {
return Controller::call('admin.'.$controller.'@edit', (array) $params);
});
There you have it!
tiffany diamond rings
/ December 16, 2012I’ll immediately clutch your rss as I can’t in finding your e-mail subscription hyperlink or newsletter service.
Do you have any? Kindly permit me recognize so that I may just
subscribe. Thanks.
ghprod
/ January 14, 2013I use it like this
Route::get('admin/(:any)/(:any?)/(:all?)', function($controller, $method = 'index', $args = null) { return Controller::call("mod_{$controller}::{$controller}@$method", array($args)); });Note, i use :all so i can have dynamic segments