Parent Class Your Code Igniter Controllers
Code Igniter offers many ways of adding functionality to your application… Libraries, Helpers, Plugins… However, there are times when you need a function to operate directly in your controller. In these cases it can be useful to create a parent class for your controllers.
One case where this makes sense is when you want all your controllers to respond to a particular message in the same way. For example you have a login form on every page and you want the user to stay on the same page once they login successfully. With a parent class you can have the login method in the parent and then send the user back to the page they were just on or just to the index.
So, how do we accomplish this? Let’s create a controller in the normal way, but we’ll call our controller “ControllerParent” with one method called login…
1 2 3 4 5 6 7 8 9 | class ControllerParent extends Controller { function login() { // Handle your login process here ... // Now we'll send them back $this->index(); } } |
Now we’ll create a site controller to work as the front end. We’ll call it sitemap and make it extend our ControllerParent class.
1 2 3 4 5 6 7 8 | // first we bring in our parent class require_once("controllerparent.php"); class Sitemap extends ControllerParent { function index() { // Display your page here } } |
Every controller that descends from our ControllerParent class will be able to answer to the url /controllername/login. Once the login method completes it sends control to the child classes index method.
You can now place a login form on each page that points to the current controller. We’re using the uri object to get the current controller name. The example form also assumes that you are using the url helper for the action…
1 2 3 4 5 | <form action="<?= site_url($this->uri->segment(1).'/login') ?>">
username:<input name="username" /><br />
password:<input name="password" /><br />
<input type="submit" value="login" />
</form> |
[...] can read the rest of this blog post by going to the original source, here [...]