If you're a keen user of Codeigniter like us you'll often have number of different pages within your application/website. Most websites follow a similar trend, a header area containing a menu with some options such as a search, a content area and a footer. An example which we'll talk about is validating the search box. As a search area is available to all pages, rather than creating form validation on each controller we can use some smart logic to extend Codeigniter's base controller to handle the validation in one central place.
Extending Codeigniter's Base Controller.
The first step is to create your own base controller to extend Codeigniter's functionality.
Create a new file MY_Controller.php and place this in the application/core folder.
Whenever you create a class with the MY_ prefix, Codeigniter's Loader class loads this after loading the core library, allowing your extended code to take presedence. We won't be changing any of Codeigniter's core system files but simply extending them leaving the system files intact.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class MY_Controller extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->check_search();
}
public function check_search()
{
//check if the form has been posted
if ($this->input->post('searchitem') !== FALSE) {
//check if we have passed validation
if ($this->form_validation->run('home/search') !== FALSE) {
//passed validation, handle the form here
}
}
}
}
Now that we have our new base class in place, we can now re-point our new/existing controllers. Take this very basic controller as an example:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Home extends MY_Controller {
public function __construct()
{
parent::__construct();
}
public function index()
{
$this->load->view('layout');
}
}
Conclusion
And there it is! You now have a controlled method of handling a site search in one central location without the need for handling validation in each of your controllers.
You can use this logic for any code that is shared by multiple controllers, but there is also many more benefits than just logic. Consider having a feedback form in your footer or setting a global sessions, any variables that are created within our new base controller will be accessible by all our controllers that extend it. Magic!
Please leave any comments or questions below.