Oliver Nassar

I can be reached at onassar@gmail.com.

For my open source work, check out github.com/onassar


PHP Reflection class: a gem I found

View more posts

In developing my own mash-up of a framework, drawing inspiration from a lot of different areas, I ran into an interesting hurdles.

Since my framework is MVC based, I ran into a problem whereby calling an action/method in a controller should only be fulfilled if the number of parameters passed in was valid. So for example, if I was dealing with a user's model, and I wanted to return the email address for the user, I would normally access it via a url pattern such as: http://www.website.com/users/details/email/

On the server side, this would access the Users controller, the details method, and pass in a parameter with the value 'email'. The method would then grab it from the db, and return it however it decided. The trick came in, however, as to validating the parameters that were passed to a controller's action/method. So for example, http://www.website.com/users/details/email/oliver/ would pass the details method/action two parameters with values 'email', and 'oliver'.

But my method/action only accepts one. So what should happen? Well ideally, a 404/error page should be pushed out, but how would PHP know that the parameter count doesn't match? You have two options. One is very intrusive, and the other is best thing ever.

  1. Intrusive: in every action, hard code something like:

    if(func_num_args() > HARDCODED_NUMBER)
        // redirect
    

    This would mean every action/method would need to do this check to make sure the right number of param's were sent in (this doesn't even take into account the minimum number of req'd parameters; only the max allowed.

  2. The best way ever: before making a call to controller's action use the Reflection class.

    This class allows you to check the parameter requirements of a call BEFORE you actually make it. So using php5's Reflection class, you can check to see how many parameters are required at a minimum (excludes required params), how many are the max, and even more fun stuff. This allows you to centralize the error handling for controller calls to the dispatcher (my naming convention for the class/method that actually makes the calls to an action/method), keep your code very clean and clear.

I did some checking, and it seems using this class isn't too expensive since this information is contained by php be default; it's just that this extension contains the API for actually accessing it.

It's a win-win situation as far as I'm concerned.