Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Codeigniter models are just utility classes?

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.)

like image 212
takteek Avatar asked Jan 21 '23 21:01

takteek


1 Answers

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();

like image 131
Phil Sturgeon Avatar answered Jan 30 '23 20:01

Phil Sturgeon