Tag Archives: PHP

How to handle headers and footers in CodeIgniter

I got this question from a reader and thought it would be useful to post for everyone:

Hi Jonathon,

I really like some of your solutions to making things simpler when using CodeIgniter. On the subject, I was wondering if you had a preference for a simple way to include headers and footers in your views. I know you can either do views within views, but that just doesn’t feel right to me. Although the advantage is only having to use one line to call your views within a controller. The method of building your views within an action by calling each view seperately also doesn’t interest me, because I’m trying to adhere to the DRY principle. I’ve also seen a solution where you create your own MY_controller and build the view that way then inherit from all your other controllers.

Do you have a recommended way to include your common views that’s simple and doesn’t require you add multiple lines of code to each controller action? I’m trying to keep my view calling to one line within each action of the controller.

Thanks,

Lee

My preference on that is simply calling views within views. It just makes sense to do it that way. If there is data that must be passed to the header and footer globally, then I would extend the Loader class with a global data function like this:

class MY_Loader extends CI_Loader {

	function MY_Loader() {
		parent::CI_Loader();
	}

	function global_view_data($key, $val) {
		# normalize the data array
		$data = (is_array($key))? $key : array($key => $val);

		# merge into the view data array
		$this->_ci_cached_vars = array_merge($this->_ci_cached_vars, $data);
	}

}

Copy that to a file called MY_Loader.php and save it in your libraries folder as described in the user guide. Once that is done you can load data which will be passed to all views globally:

$this->load->global_view_data($stuff);

Note: I have found that including views within views is aggravating without a helper function, so I wrote the Modularity plugin to help with that.

Handling errors inside shutdown functions

Using register_shutdown_function() to do stuff on script shutdown requires special error handling. Normal error handling does not work within the function called, so if an error occurs inside your shutdown function you get this nondescript error:

Fatal error: Exception thrown without a stack frame in Unknown on line 0

The solution was to catch the exception and call the exception handler directly:

function shutdown_handler() {

	try {
		//... do stuff
	}
	catch(Exception $e) {
		die($e);
	}

}