Object-oriented – PHP MVC Display many records – model logic

mvcobject-orientedPHP

I bet this question has been asked already but I can't form my thought as you can see from the title, so I couldn't find anything. I am working with MVC for quite some time now and I'm pretty happy to say that when things work out good they are nearly perfect ( in my eyes ), however I never feel like I'm doing a good job at this particular task.

Say I have my model for a user, with all of its properties and methods like,

namespace Models;

class User {

    private $id;
    private $name;

    public function __get($name){
        return $this->$name;
    }

    public function setName($name){
        $this->name = $name;
        return true;
    }

    public function save(){
        // Save user to database
    }

    public function getById($id){
        // fill properties from database with id $id
    }

}

All fine all good, but then when I need to display a list of users for, say a search page or something, I always end up doing something like adding a static method getUsers or something that returns an array of \Models\User objects which just doesn't give me that "good code" feeling, hopefully you know what I mean. It gets even worse when I need to only get a couple of columns from the database, then the greater number of properties is empty and just feels like I'm messing up.

I want to ask you what is the correct way to do this?

Best Answer

I don't know if this is what you're looking for but here goes.

Methods like save, get, getBy, getAll, etc, are generic and would ideally work across multiple models. For the most part, the only difference is going to be SPECIFICALLY where that data is. So why not make a super model of sorts for all your models to extend.

class Super_Model
{
    public $table; // this will be defined in the model

    public function getAll(){
        // returns all from $table
    }

    // etc
}

class User_Model extends Super_Model
{
    public function __construct()
    {
        $this->table = 'Users';
    }
}

Now you can do the following without having to define getUsers:

$user_model = new User_Model();
$users = $user_model->getAll();