Skip to content

Instantly share code, notes, and snippets.

@DakuTree
Created February 11, 2016 14:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DakuTree/153b85190de414079009 to your computer and use it in GitHub Desktop.
Save DakuTree/153b85190de414079009 to your computer and use it in GitHub Desktop.
CodeIgniter - Show error if user profile does not exist (without redirecting)
<?php defined('BASEPATH') OR exit('No direct script access allowed');
/*
I wanted a single controller to handle my profile page, as well as any sub pages that may appear. At the same time, I wanted to avoid any possible code duplication.
The code duplication appears when you want to validate the username passed by the URI. Each and every method would have to check this, and we can't just check this in __construct since the method would be called anyway.
We could always do a redirect(), but honestly I don't think that feels right on a invalid profile page. I'd rather stay on the same URL and show an error.
To get all of this done, we need to use _remap. _remap is called after __construct, but before the method. We can now have the construct validate the username & set the variable if exists, and remap only call the method if it does exist.
If the username doesn't exist, the URI method is not called, and instead we call a fallback method.
All of this omits the need to do any username validating within the page methods, as it's all done before they are even called.
This is actually fairly simple stuff, but I spent a good few hours figuring out how to solve this.
Hopefully this solves anyone else with the same issue.
*/
class Profile extends CI_Controller {
private $username;
public function __construct() {
parent::__construct();
//Replace this with your own way to check if the username exists.
if($this->User->username_exists($this->uri->segment(2))) {
$this->username = $this->uri->segment(2);
}
}
public function index() {
//render stuff
}
public function another_page() {
//render stuff
}
public function and_another_page() {
//render stuff
}
public function _fallback_method() {
//This is only called when the username does not exist
//render
}
public function _remap($method, $params = array()) {
//Only load profile pages if username exists, otherwise load fallback error page.
if(method_exists($this, $method) && $this->username) {
return call_user_func_array(array($this, $method), $params);
}
$this->_fallback_method();
}
}
<?php
//Example routes.
//There is no need to pass username to the URI here, since we're checking the segment instead.
$route['profile/(?:[a-zA-Z0-9_-]{4,15})'] = 'User/Profile/index';
$route['profile/(?:[a-zA-Z0-9_-]{4,15})/another_page'] = 'User/Profile/another_page';
$route['profile/(?:[a-zA-Z0-9_-]{4,15})/and_another_page'] = 'User/Profile/and_another_page';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment