One of the most important methods I’ve found in CodeIgnitor is the
_remap() method. When you use it within a controller it hiijacks all other methods and does your bidding.
This is great when you have a controller
Article.php and you want the 2nd value in your urls to be the ID number or a unique url encoded title or ‘slug’ for the article being queried. You can’t be expected to build a method each time you publish an article. Plus you’ll likely want your
_remap() method to query a database and display the article that way.
The problem I’ve run into a few times is that if I want to use both
_remap() and named functions it is a hassle.
Example: With my article example if I want a url and page:
/article/search, while still having
/article/writing-smart-codeignitor-controllers query from the database based on the string after
/article/ I have had to build exceptions within the
_remap() method to redirect explicitly to other methods withing the controller class.
To better outline that example:
These urls should access their methods in the Article (submit and search, respectively:
These urls are the reason we have to use
_remap() to begin with cause they are dynamic based on the contents of a database:
Then I found a better solution:
This amazing snippet of code will first check to see if a method or function by that name (
$method) exists within the current class(
$this), and if it does it will use that method. We return false immediately after we call that method using PHP’s built in
call_user_func() function so nothing else in the
_remap() method is executed. Otherwise you can remap as usual!
Note: You could also use CodeIgniter’s URI routing but that’s not something I’m terribly familiar with so I’ll stick to
_remap() for the time being!