开发者

CodeIgniter $this->load->vars($array)

开发者 https://www.devze.com 2023-03-17 19:27 出处:网络
CodeIgniter has a method $thi开发者_如何学Pythons->load->vars($array) that is ideally used in the parent Controller to provide global access to system variables directly in the view. For example

CodeIgniter has a method $thi开发者_如何学Pythons->load->vars($array) that is ideally used in the parent Controller to provide global access to system variables directly in the view. For example:

$this->data['username'] = "john";
$this->load->vars($this->data);

Then in the view, you can easily access john by echoing $username.

My question is, is it possible to use $this->load->vars($array) from within a Model instead of a Controller? This will allow me to abstract away some details from my Controller, making it cleaner. What changes would I have to make to get this working? Would you recommend it; do you think it breaks MVC?

Also, I'm using Datamapper ORM, so my models actually extend the Datamapper object and not the Model object.

Thanks!


Is it possible to use $this->load->vars($array) from within a Model instead of a Controller?

As mentioned, yes you can do this, you can even load a view from a Model, or even run $this->load->vars() in a view and load yet another view.

This will allow me to abstract away some details from my Controller, making it cleaner.

This is like sweeping the dirt under the rug, it didn't go away - it just went somewhere else where you are bound to deal with it later.

Would you recommend it; do you think it breaks MVC?

It's not going to "break" anything, but it implies that maybe your concept of MVC is somewhat broken. If it has nothing do do with the data layer and everything to do with the view layer, it doesn't belong in the Model. There's a good chance there may be some other stuff that doesn't quite belong there as well...

I'm using Datamapper ORM, so my models actually extend the Datamapper object and not the Model object.

You may need to call get_instance() and assign it to a variable or class property for use in DM models, so you can access the Codeigniter object.

Example: $CI =& get_instance(); $CI->load->vars();

Suggestion:

Return the data from the Model in the simplest, most reusable form possible, and then assign it to the view variables in the Controller. If I'm hunting down the source of some variables in a view file, the last place I'd look for them is in the Model. You may end up revisiting this project in the future, so try to be consistent as much as you can, and stick to the suggested, expected practices.

0

精彩评论

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

关注公众号