开发者

PHP - Solving problems with Closures and Reflection

I needed to create dynamic breadCrumbs that must be realized automatically by the application. So I have the following structure in the URL for navagation: nav=user.listPMs.readPM&args=5

then i could have a function-file whose sole purpose would be to define the user.listPMs.readPM function itself:

file: nav/user.listPMs.readPM.php

function readPM($msgId)
{
 /*code here*/
}

Of course this ends up cluttering the global scope since i'm not wrapping the function withing a class or using namespaces. The best solution here seems to be namespacing it, no doubt right? But I also thought of another one:

file: nav/user.listPMs.readPM.php

return function($msgId)
{
 /*code here*/
};

Yep, that simple, the file is simply returning an anonymous function. I think this is 开发者_如何学Pythonamazing because i don't need to care about naming it - since i've already properly named the file that contains it, creating a user function and yet having to name it would seem just redundant. Then in the index I would have this little dirty trick:

file: index.php

if($closure = @(include 'nav/'.$_GET['nav']))
{
 if($closure instanceof Closure)
 {
  $obj = new ReflectionFunction($closure);
  $args = explode(',',@$_GET['args']);
  if($obj->getNumberOfParameters($obj)<=count($args))
   call_user_func_array($closure,$args);
  else
   die('Arguments not matching or something...');
 } else {
  die('Bad call or something...');
 }
} else {
 die('Bad request etc.');
}

Don't even need to mention that the breadCrumbs can be nicely built latter just by parsing the value within the $_GET['nav'] variable.

So, what do you think, is there a better solution to this problem? Have you found another way to explore Closures and/or Reflection?


I like the basic idea. But the implementation is pretty much terrible. Imagine that I set nav=../../../../../../etc/passwd. That would (depending on your server configuration) allow me to access your password file, which certainly is no good.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜