4

I'm relatively new to CodeIgniter, and so far my project is created entirely using Controllers and Views. However, as it's getting more complex, I'm finding that there are certain functions that I've copy-pasted into multiple controllers -- this is hardly ideal as editing one requires remembering to edit all of the others as well.

There is a plethora of CI features that I know nothing about - models, helpers, extending "Controller", etc. etc. Where should I look to in order to accomplish the above? I suppose I could also import() a block of code directly, although I get the feeling that this is not "the CodeIgniter Way".

3 Answers 3

4

Put all your "utility" functions into a "helper manager" and access that.

http://codeigniter.com/user_guide/general/helpers.html

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the link. The article doesn't say anything about how to create my own helpers. Is it as easy as creating a file in the helpers folder that doesn't begin with "MY_"?
What happens if you load two helpers that have the same function name? Which function will be executed when called?
You should extend the "Helper" that has the same function name (i.e. MY_array_helper.php). If you don't, I'm not certain, but most likely it will call the last defined method in PHP.
2

Or create a base controller, and extend other controllers from it.

I'm sure Phil Sturgeon has a guide on it: http://philsturgeon.co.uk/blog/2010/02/CodeIgniter-Base-Classes-Keeping-it-DRY

1 Comment

Phil has a guide on everything
2

base_controller.php

<?php
class Base_Controller extends CI_Controller {
    function __construct()
    {
        parent::__construct();
    }
    function base_function(){

        }
}
?>

other_controller.php

<?php
require_once('base_controller.php');
class Other_Controller extends Base_Controller{
    function __construct()
    {
        parent::__construct();
    }
    function index()
    {
    $this->base_function(); 
    }
}
?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.