user622378
user622378

Reputation: 2336

CodeIgniter controllers, how to avoid repeating code?

Every page has dynamic sidebar (column) such as 10 recent articles. It show list in title.

I have to repeat same block of code in every method (action) in the controllers files.

Eg:

<?php
class Blog extends CI_Controller {
    function index()
    {
        // Sidebar code block
            //some code for index
    }
}

class Signup extends CI_Controller {
    function index()
    {
        // Sidebar code block
            //some code for index
    }

    function login()
    {
        // Sidebar code block
            //some code for login
    }
}
?>

In the view folder. I have a sidebar file

There must be a way to void repeating.

Upvotes: 2

Views: 810

Answers (2)

Dalmas
Dalmas

Reputation: 26547

Maybe create a base class and put your function inside it?

<?php
class BaseClass extends CI_Controller {
    function index()
    {
        // Sidebar code block
            //some code for index
    }

}

class Blog extends BaseClass { // Extend your classes from the base class
}

class Signup extends BaseClass {
    function login()
    {
        // Sidebar code block
            //some code for login
    }
}
?>

Upvotes: 3

rabidmachine9
rabidmachine9

Reputation: 7965

what if you declare it in the constructor , or in one of your config files? http://codeigniter.com/user_guide/libraries/config.html

Upvotes: 0

Related Questions