1
\$\begingroup\$

I have multiple models which all have the same functions in my framework. I decided to create one "parent" model and all of my other models would extend and inherit its functions like this.

My other models would be like this:

class Games_model extends MY_Model {
    protected $table = 'games'; 
    protected $_default_select = array();
    protected $_default_join = array();

    public function __construct()  {
        $this->_default_select = array(
            $this->table.'.*',
            $this->table.'.id as id',
            $this->table.'.name as name',
            'categories.id as cat_id',
            'categories.name AS cat_name'
        );
        $this->_default_join = array('categories', 'categories.id = fiches.console_id', 'left');
    }
}

Here's how I use it:

$this->games_model->limit(30,0)->where(array('categorie_id' => 1))->get_list()->result();

Is it a better idea to do like that or to have all the code of MY_Model in Games_model?

\$\endgroup\$
  • \$\begingroup\$ Always a good idea have intermediate layer of classes that hold the same behaviour for child classes, but read my answer below for more details of your implementation. \$\endgroup\$ – Chococroc May 24 '14 at 17:24
2
\$\begingroup\$

Well, having a parent model that is extended for all your model classes is always a good idea if they all share the same behaviour and help you with your development. I have implemented a similar approximation within my models and I'm doing something similar to what you do, but instead of writing the query in the controller, I call to the model to handle the retrieve of the data.

Doing as you do it, you have to write all the time the same kind of query in your controller, losing the MVC pattern. Let's say you want to retrieve the values of categories, in a point of your controller you'd have:

$this->games_model->limit(30,0)->where(array('categorie_id' => 1))->get_list()->result();

If you want to retrieve the categories in other line of your controller, you'll have to write the same sentence, and... what if, in some point of your development, you wanted to change the field categorie_id to, let's say, super_categorie_id? You'd have to do it in all the calls in your application code... You lost all the value the M in MVC is offering, isolate management of data in the Model layer.

So, I'd keep the extension, but writing the methods for reading with is proper filters INSIDE of the child class, and pass it only the data not needed for filtering (as limit) as a parameter, and set them to a default.

I don't know if I clearly explained myself, any doubt write a comment, ;D

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.