Sunday, August 12, 2007
One of the great things about Code Igniter is the fleixibility of the framework. I have recently used CI for a major project for Tourism Western Australia called WATV which showcases tourism and events in WA through the use of video. The site was built using Code Igniter and jQuery for the ajax calls and visual effects. This is the biggest project that I have worked on using Code Igniter so I learned a lot, but one thing I didn't learn until after we had actually finished the development of the first phase was using the _remap() function in the controllers and instead wrote my own code to deal with my custom routing when all the hard work has already been done and exists in the framework so I will need to revise the controllers for the next phase.When you are using custom routing you often come across a problem, you have specified that any url parameters after a certain controller name will be used by a certain method, now when you try to introduce another method it gets overidden by your routing. For example say you have a users controller and you want any username after /users/ in your url to look up a user. You could set up a custom route such as:
$route['users/:any'] = "users/index";
So now your index method in the users controller will check the url parameter against the user table. Now saw you want to add a method called edit, what will happen?
/users/edit/username
Well your route will send edit as a username to your index controller and break your method, so you have to check that the url parameter isn't "edit" and maybe run a different method in your controller:
if ($username == "edit") {
$user = $this->uri->segment(2);
$this->edit($user);
}
See how messy this would become one you start adding methods? Well luckily the clever coders who devised CI came up with a simple solution, _remap(). Now instead of using the custom routing you can remove that and set up the _remap() function in your controller:
function _remap($method)
{
if ($method == 'edit' || $method == 'update')
{
$this->$method();
}
else
{
$this->default_method();
}
}
Now what happens is you override the default controller action by catching the first url parameter and checking if it is a method name or something else like a username and if so calls another method of your choosing! Easy, and a lot cleaner than manually catching each parameter yourself. Hope this helps anyone faced with a similar problem!
Labels: Code Igniter
Jon 9:38 AM Permalink
Comments:
Hi ,
It's nice to know that you use jquery
in CI. I am new in jquery and CI.I am looking for some code for
real ajax application where use jquery and ci.
Can you send small part of code of your applications. where you use ajax. It will be very help for my projects.
Thanks
Saidur Rahman
www.saidur.wordpress.com

