I’m writing my own MVC framework in PHP, just for learning purposes. It wasn’t really hard to have a router/dispatcher class to call the right controller/action etc.
But now i’m at the part where i’m going to use models. Or actually, the model layer. But there’s something that confuses me.
Alot of other MVC frameworks have a ‘BaseModel’. I’ve read that this is actually bad practise, because the “Model” shouldn’t be seen as another class. But as a real ‘layer’, which can contain things like the ‘mapper’ pattern or ‘repository’ pattern etc.
But to be honest, i don’t see any advantages in that. To me, a ‘BaseModel’ class seems to be the fastest way to go, with the same results.
I can simply do something like:
class User extends BaseModel
{
// the GetUserBy* could easily be something that's handled by the
// BaseModel class, like in the Repo pattern.
public function getUserByName ( $name )
{
// no error handling of any kind, just for simplicity
return $this->db->exec("SELECT * FROM users WHERE name='".$name."'");
}
// $data = array
public function saveUser ( $data )
{
// Make sure no extra fields are added to the array
$user = array ( 'name' => $data['name'],
'address' => $data['address']);
$this->db->autoSave ( $user );
}
}
But if i’d go for a repository pattern then i have to create the following:
Repositories
Entities
DAO
Entities have Aggregates to other repositories. So basically i’m manually writing out my entire database scheme to objects…
In the end, what’s the difference??? Except that i probably could have saved alot of time by simply using a BaseModel class…
But why is it still considered to be a bad thing then?? It’s not that the repo pattern decouples my application more then i’m doing now. Because to me, those patterns mentioned above seem to be highly overrated. It probably would only work in an application that has a shared state; Save objects locally (in the repository) and commit them later on.
That’s why i think no one can really answer this…
But i’m still hoping to see a decent answer that makes me go: “ahhhh… What was i thinking….”. But if not, then i’m sure about my case that the BaseModel isn’t a bad thing at all and that most bloggers are just a bunch of sheeps 🙂
Your application is tightly coupled to SQL database components (which are, in effect, acting as your mapper). However, despite this, your design is much more like a Repository than an Active Record approach (which is likely what most of these bloggers you refer to are griping about).
Active records encapsulate not only the data, but also the database access:
It’s nicer to have the record objects be unaware of the persistence layer (separation of concerns). Your “base” does just that by returning arrays of user data and when those arrays are modified, they must be passed back to the user “base” for saving. You could change your naming to:
There’s nothing wrong with having a base repo.