1

I read an article talking about how to create domain objects here. The author is explaining how to design the classes. To put itin a nutshell, you have a class per real world entity (i.e class User, Comment, Post, etc) and getters + setters (that check the validity of the data).

For one to many relations, for exemple all the comments related to a single post, the author uses an array to store instances of the class Comment into an instance of Post class. But here is what i don't understand :

$post = new Post();

$post->addComment( new Comment() );
$post->addComment( new Comment() );
$post->addComment( new Comment() );

$postModel = new PostModel();
$postModel->insert( $post ); // Should also insert (or not !) the added comments.

When we're going to insert that new post, the associated comments may or may not actually exist (my example doesn't make a lot of sense since you can only comment posts that exist, but that's just an example). Should the model check each if the added comments exists before adding them ?

Also if you know an article that would explain how to write a model properly, in the same phylosophy used by the author of the article above, that would be nice.

tereško
  • 58,060
  • 25
  • 98
  • 150
Virus721
  • 8,061
  • 12
  • 67
  • 123
  • No, the model should not check it, it's a controller's job – Royal Bg Oct 07 '13 at 20:10
  • Thanks for your comment. Why is it the controller's job ? – Virus721 Oct 07 '13 at 20:11
  • Because of the MVC's logic: http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller your `insert()` method in the model should be called after successful response from the controller – Royal Bg Oct 07 '13 at 20:15
  • And what if only some of the comments to insert exist. Should the controller specify which ones or should the whole insert be aborted ? – Virus721 Oct 07 '13 at 20:16
  • Depends on what you want to achieve. But both cases are controller's job. If it's not crucial to continue if 1 of 10 models does not exist, don't stop the app. – Royal Bg Oct 07 '13 at 20:21
  • @Virus721 this has nothing to do with "models". That `PostModel` class is actually a [data mapper](http://martinfowler.com/eaaCatalog/dataMapper.html). And none of this should be in the controllers. Interaction between domain objects and persistence abstraction should be contained in services. – tereško Oct 08 '13 at 09:47
  • All this seems uselessly complicated to me. I'm not even sure to get the advantages of all these layers over a basic associative array passed to an insert function, except for the sexy OO syntax. There must be something i don't understand. – Virus721 Oct 09 '13 at 14:35

1 Answers1

-1

I think for first you need create post and then add comment,

$post = new Post();
$post->populate($postData);
$post->save();
$post->addComment( new Comment() );

or choose in what post you add comment

$post = new Post($idPost);
$post->addComment( new Comment() );
Sergey Krivov
  • 372
  • 1
  • 4