Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Flexible routing #304

Closed
wants to merge 4 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 64 additions & 0 deletions src/Klein/Klein.php
Original file line number Diff line number Diff line change
Expand Up @@ -391,6 +391,70 @@ public function with($namespace, $routes)
$this->route_factory->setNamespace($previous);
}

/**
* Collect a set of routes under a common namespace
*
* The routes may be passed in as either a callable (which holds the route definitions),
* or as a string of a filename, of which to "include" under the Klein router scope with
* flexible ability to split route from controller name.
*
* <code>
* $router = new Klein();
*
* $router->withFlex( 'user', '/users', function($router) {
* $router->respond( '/', function() {
* // do something interesting
* });
* $router->respond( '/[i:id]', function() {
* // do something different
* });
* });
*
* $router->withFlex( array( 'UserController', 'TestController' ), '/home', function($router) {
* $router->respond( '/users', function() {
* return $app->UserController->index();
* });
* $router->respond( '/tests', function() {
* return $app->TestController->index();
* });
* });
*
* $router->withFlex( 'car', '/cars', __DIR__ . '/routes/cars.php');
* </code>
*
* @param $class The Controller class name
* @param string $namespace The namespace under which to collect the routes
* @param callable|string $routes The defined routes callable or filename to collect under the namespace
* @return void
*/
public function withFlex( $class, $namespace, $routes ) {

if ( is_array( $class ) ) {

foreach ( $class as $key => $c ) {

if ( class_exists( $c ) ) {

$this->app->{$c} = new $c;

}

}

} else {

if ( class_exists( $class ) ) {

$this->app->{$class} = new $class;

}

}

return $this->with( $namespace, $routes );

}

/**
* Dispatch the request to the appropriate route(s)
*
Expand Down