tags:

views:

346

answers:

2

Let's say I have a User model. Would I put methods on the model itself, or as a template so I can access it from the user table object?

In other words, which is more preferable:

$u=new User();
$u->register($username, $password, $email);

or

$userTable = Doctrine::getTable('User');
$userTable->register($username, $password, $email);

My instinct would be the second one, since it logically makes more sense, but what about things like password changing, logging in, etc? Should I really put those on the User model while I keep things like register on the user table object?

+2  A: 

Generally, if things relate to a specific instance of a User, ie: me or you, they belong in the User class. If they relate to a group of users, or we don't have the user yet (ie: loading them from the database), then they belong in the Table class.

I would do your example as:

class UserTable {
  function register($username, $password, $email) {
    $user = new User;
    $user->username = $username;
    $user->password = $password;
    $user->email = $email;
    $user->save():
  }
}

People will argue about where some things belong though, and saving is one of them! I know Propel, which is another similar PHP ORM, includes a save method in its Table equivalent, as well as in its Object equivalent, and your registration is sort of analagous to this. So sure someone will be along to argue the other side soon!

To answer the other questions, in my opinion:

Password change belongs in the User, definitely - you are changing a user's password, its just changing a field.

Logging in should be in the table class - its a specialised case of retrieve.

benlumley
+2  A: 

It probably won't be a complete answer to your question, but you might be interested by taking a look at the slides if the Play-Doh: Modelling Your Objects conference that Matthew Weier o'phinney published a few days ago ; there contain nice stuff that could make you think about Models ;-)

(They made me think.. But I still cannot give a definitive answer to your question : I'd say "it depends"... But not sure on what ^^ )

Probably, in the situation of a big application, I would use one more layer :

  • Model, to access the data
  • "Service", to manipulate it ; being able to do more than what I would put in the Model... And not having that in the Controller, where it doesn't belong
  • And, of course, Controller and Views

But you'll never get everyone to agree... So I'd say choose one way, and make sure everyone in your team does that way for the whole project : there's nothing worse than too many different ways mixed in one project/application !

Pascal MARTIN