Hi all
I've come across a requirement which I'm sure is not unique. I'd like to be able to generate URLs based on my PHP routes, but in Javascript. I could easily achieve this with an ajax call, but it would be impractical to make a server call every time I needed a URL generated.
My first-effort, crude, solution is to write a bunch of JS functions:
function URL_HOME () { return '/'; }
function URL_LOGIN() { return '/login'; }
function URL_PROFILE(username) { return '/'+encodeURI(username); }
But I think there should be a more elegant way to generate this capability straight out of my router. So, as a possible use-case:
// router
class My_Controller_Router extends Zend_Controller_Router_Rewrite
{
public function __construct()
{
parent::__construct();
$this->addRoute('profile', new Zend_Controller_Router_Route(':username', array('controller' => 'user', 'action' => 'profile')));
}
}
// ...somewhere else, in a view perhaps:
$router = new My_Controller_Router();
$router->toJavascript();
Which might spit out (in JS):
function assemble(parms, name) {
function profile(parms) {
return '/'+encodeURI(parms.username);
}
// ... other route-functions -- or possibly just a list of regular expressions
try {
return eval(name)(parms);
}
catch (e) {
return null;
}
}
And then I can do:
var profileUrl = assemble({ username: 'Neil' }, 'profile');
Thoughts?
- Neil
没有评论:
发表评论