我的博客捆绑包中有一个Post实体。帖子可以有很多评论。当我创建一个新的评论实体来附加到帖子时,我必须设置一组属性,例如
$comment->setTimestamp( new 'DateTime() );
$comment->setUserId( $this->getUser()->getId() );
$comment->setHost( $this->getClientIP() );
默认时区在实体的构造函数中很容易。在构造实体时,如何自动设置userid和clientip?getClientIP是目前控制器中的一个函数。这应该是服务。我可以有一个为我创建评论的工厂吗?
在我看来,你最好的选择是class CommentFactory extends EntityFactory
。
工厂将负责为您创建实体,您传递所需的实体(如用户实体),它将为您返回新对象:
$commentFactory = new CommentFactory($user, $client, $whatever);
$comment = $commentFactory->getNewComment();
您可以从实体构造中调用任何实体方法,也可以将控制器中的任何内容传递给注释的新实例。例如,在控制器操作中获取时间戳、userid和host,并将它们作为参数传递给Comment实体的构造。调用构造中的setter方法。
您可以在控制器中为创建助手函数
protected function getNewComment() {
$comment = new Comment();
$comment->setTimestamp( new 'DateTime() );
$comment->setUserId( $this->getUser()->getId() );
$comment->setHost( $this->getClientIP() );
return $comment;
}
然后
$comment = $this->getNewComment();