mrjgreen / phroute

A super fast PHP router, with route parameters, restful controllers, filters and reverse routing.
Other
710 stars 96 forks source link

Passing Routing Variables To Global Scope #39

Open fiatux opened 8 years ago

fiatux commented 8 years ago

I need to get routing parameters available in the global scope. I am not using controllers in a project, so I am including script file based on route rules using dispatcher.

Basically, when I set route rules as

$router->any('/page', function(){
    return '/path/to/page.php';
});

I include the returned script path as

$dispatcher = new Phroute\Phroute\Dispatcher($router->getData());
$response = $dispatcher->dispatch($_SERVER['REQUEST_METHOD'], parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));
include $response;

I cannot include script in the callback function due to other reasons. So the problem for me is to pass route parameters in dynamic routes to outside of the callback function's scope. Example:

$router->any('/blog/{post:[a-zA-Z0-9+_\-\.]+}', function($post){
    return '/path/to/post.php';
});

I need $post parameters out of callback function

My best attempt is using get_defined_vars() as a generic solution:

$router->any('/blog/{post:[a-zA-Z0-9+_\-\.]+}', function($post){
    return array('path/to/post.php',get_defined_vars());
});

So that I can get $post at dispatcher.

Is there any better method to get route parameters at the dispatcher level?

mrjgreen commented 8 years ago

Okay... I'm not sure what the "other reasons" you've described are but I've worked on enough legacy projects to understand that you aren't always able to make the changes you'd like :) However, it does seem that you are trying to do something a bit unorthodox here. Is there any chance you could expand on why you aren't able to include your view as a template such as this?

function template($tplFile, $vars = array())
{
  extract($vars);
  ob_start();
  require($tplFile);
  return ob_get_clean();
}

//...

$router->any('/blog/{post:[a-zA-Z0-9+_\-\.]+}', function($post){
    template('path/to/post.php', $post);
});

Alternatively swap the templating contents for an engine like Twig etc...

Sorry if this is no help... Trying to get an understanding of your use case :)