Xeoncross
Xeoncross

Reputation: 57194

Is controller-based class loading better? (CodeIgniter/KohanaPHP/etc..)

If you have worked with some of the frameworks like CodeIgniter or KohanaPHP, then you probably have seen that they are built so that the controller loads everything. Therefore, if you are in a library and wish to load additional resources you must get a copy of the controller instance and then use that to load the additional classes.

$this->c = get_instance();
$this->c->load->library('other_lib');

I'm wonding if it would be bad form to offload the class loading to another library so that you do not have to be tied to the controller instance. For example,

$this->other_lib = load::library('other_lib');
//vs
$this->load->library('other_lib');

Am I violating any MVC principals here? I know loading resources from models is bad - but what about other library packages that the controller isn't involved in?

Upvotes: 0

Views: 313

Answers (1)

rojoca
rojoca

Reputation: 11190

If you're developing a library which needs to access additional resources, then add those resources as dependencies of your library. This means, when you need a class from your library, pass in any required resources when it is created via the constructor.

For example:

class MyLib {
    public function __construct(DB $db) {
        $this->db = $db;
    }
}

Upvotes: 1

Related Questions