When I was looking through frameworks to use, I was weighing some of the choice based on the frameworks ability to route calls based on HTTP Request Methods. Call me a pedant, but I believe that a POST to a page should be a whole different plate of spaghetti from a GET of the page. GET’d pages should get and retrieve information and POST’d pages should perform actions.

From the MVCs available, there weren’t any available (that I saw), that off the shelf allowed for this kind of functionality. I chose CodeIgniter and figured I would just have separate named methods for POST or GET.

As I said in a previous post, my exposure to CodeIgniter was based on old tutorials I had pulled from various tutorial sites. Once, I found some more recent tutorials that led to many an aha moment. This is one of those moments.

By extending the CI_Router class with our MY_Router class, we can modify the fetch_method method to return our method name and the HTTP Request Method. In 9 lines of code, you can now have an index_get method and an index_post method to handle exactly what they need to handle.

Add  this to or create your /application/core/MY_Controller.php file

class MY_Router extends CI_Router {
  function fetch_method(){
    $request = strtolower($_SERVER['REQUEST_METHOD']);
    if ($this->method == $this->fetch_class()) {
      $method = 'index_' . $request;
    } else {
      $method = $this->method . '_' . $request;
    }
    return $method;
  }
}

Next, just identify the Request Method you would like to allow on your class methods by adding “_get” or “_post” to the end of the method name. That should be it. You can now create individual methods that look like this:

public function index_post() {
  /*Drop database schema*/
  redirect(uri_string(), 'location', 301);
}
public function index_get() {
  /*Display what just happened*/
}

This prevents the POST’d page from being refreshed and keeps the retrieval logic separate. I haven’t tested how CI handles HEAD requests, but the next step is to keep logic from being performed and only 404 if the database cannot be connected.