views:

161

answers:

1

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?

+1  A: 

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;
    }
}
rojoca
Suppose that library has variable dependencies (DB layers/image libs) and doesn't know what classes are needed until runtime?
Xeoncross
Xeon - You can usually structure your application in a way so that this is known at compile time. If you can't, it's often a sign that you didn't partition the libraries properly. That said, in situations where you can't, you can use a factory/registry instead.
troelskn
I think your missing the point. Since this is a controller that is possibly unrelated to the library projects it is loading - it is total disconnected from the logic they imply and therefore cannot know what objects should be passed when loaded. This is better handled by the library package itself which has two options - get the controller instance to load the other classes - or do load them itself.
Xeoncross
Xeon - I see your point about the disconnect, and when you're constrained by a framework you do need workarounds. That said, when you design a library it should not have any dependencies on a framework or some kind of singleton registry. It should have all its dependencies passed to it on creation. Use the controller to load a factory (in which you control the creation logic) and from that retrieve objects from your library. Once again, the aim is to keep the library separate from the framework.
rojoca