Codeigniter models are just utility classes?

2019-06-24 06:26发布

In the MVC that I'm accustomed to, model classes (usually) represent tables and objects of these classes are rows/domain objects. I don't understand in CodeIgniter why model classes appear to just be singleton utility classes. It feels wrong writing

$data = array('text' => 'hello');
$this->commentModel->insert($data);

instead of

$comment = new Comment();
$comment->text = 'hello';
$comment->save();

Can someone explain why CodeIgniter does models this way and make me feel better about it? (Or tell me what I can do to fix it.)

3条回答
三岁会撩人
2楼-- · 2019-06-24 06:41

CodeIgniter doesn't include an ORM.

I would suggest to see at Doctrine that can be easily integrated with CI: http://codeigniter.com/wiki/Using_Doctrine_with_Code_Igniter/

查看更多
虎瘦雄心在
3楼-- · 2019-06-24 06:43

You can check out my articles on how to use Doctrine (ORM) with Codeigniter.

Part 1 of 11: http://www.phpandstuff.com/articles/codeigniter-doctrine-from-scratch-day-1-install-and-setup

查看更多
Viruses.
4楼-- · 2019-06-24 06:49

Models in CodeIgniter are designed using singleton pattern you're right. While this seems confusing to many people who are used to working with a more PHP OOP approach, there are a few reasons.

The first most simple is that you can load a model just the once and have it available in the super-global for use throughout the system.

That's the only real plus here, the rest are apologetic explanations.

CI was built in 2006 with PHP 4 support as a main priority.

This is only just starting to change now EllisLab has dropped PHP 4 support from CI 2.0, but for now, that's how the framework works.

You can of course load a model then use whatever PHP 5 syntax you like for your models.

$this->load->model('comment');

$comment = new Comment(); $comment->text = 'hello'; $comment->save();

查看更多
登录 后发表回答