I’m codeing in codeigintier but this question equally applies to any MVC framework.
How do I abstract the logic for determining if a parameter for a controller method is valid across mutlple methods that take some of the same parameters?
EDIT: More detail
For example in the application I’m building at the moment there are multiple ‘sites’ and nearly all the data in different tables belongs to a site and a user can only view a subset of the sites. So lots of my methods start method($site_id,...) so it would be really nice if I was able to have a pre_controller hook which could look at the parameters for the methods and detect if there was a $site_id in the parameters, and if there was check the permissions.
The problem is that not all the methods in those controllers will all have a $site_id parameter, so I cannot do the checking automatically in the constructor of my extension of CI_Controller
For CodeIgniter one way of going about abstracting the logic is to create a super class as such:
All your controllers that you want to share the same logic should then extend MY_Controller instead of CI_Controller
Now in your MY_Controller you can create functions to “handle incorrect parameters across multiple methods”.
UPDATE
Your controller function params are coming from your route. e.g.
mydomain.com/mycontroller/myfunction/param1/param2/would go to themycontrollerpublic function myfunction($param1, $param2)$site_idis just your variable naming. You can’t tell what it’s named and even if you could i doubt it’s a good idea to based any logic on how you name your variables.A simple way is just to explicitly call the validating function (stored once in your base controller, a library or a helper) in each controller’s function that require it, that gives you fine grain control.
UPDATE
Generally, to gain automation you must give up flexibly and follow conventions.
so to not go the “use helper” way and to go the auto detect way… create your own convention.
in your base controller use $this->uri->segment(n) to check if a certain URL pattern exist, if it does you know that the site_id param is incoming and that you can run automatic validation on it.