Skip to content

Instantly share code, notes, and snippets.

@DakuTree

DakuTree/Profile.php

Created Feb 11, 2016
Embed
What would you like to do?
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