开发者

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->l开发者_JAVA百科oad->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?


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;
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜