I'm confused about using repository pattern when it comes to saving data. I've written discussion board so when user creates a new thread I need to save many objects (relations). Basically I need to:
- Create new record in
topics
table - Create new record in
posts
table - Assign post's attachments
- Add user ID to
subscribers
table (so he/she can recieve notifications about new replies)
It might look like this:
$topic = $topicRepository->create($request->all()); // $topic is instance of Eloquent model
$post = $postRepository->create($request->all() + ['topic_id' => $topic->id]);
// ... save attachments etc
$url = route('topic', [$topic->id, $post->id]) . '#post' . $post->id; // build URL to new post
// I have Topic and Post model: creating notification ...
BUT I have feeling I'm doing it wrong. Shouldn't I create new method in my repository that can create new thread (add new records to topics
, posts
tables) and keep my controller clean?
Maybe like this?
// TopicRepository.php:
public function createWithPost($request)
{
$topic = Topic::create($request);
$post = $topic->posts()->create($request);
// ...
return $post;
}
// Topic.php (model):
class Topic extends Eloquent
{
public function posts()
{
return $this->hasMany('Post');
}
}
// Post.php (model);
class Post extends Eloquent
{
public function topic()
{
return $this->belongsTo('Topic');
}
}
// controller:
$post = $topicRepository->createWithPost($request->all()); // $post is instance of Eloquen model
$url = route('topic', [$post->topic()->id, $post->id]) . '#post' . $post->id; // build URL to new post
So questions are:
What is a good approach to save relations in repository pattern?
Should repository pattern deal with saving all relations?
Route model binding and repository pattern
Route model binding is a great feature in Laravel. Doesn't it break repository pattern rules? I mean: should we write:
public function index($topicId, $postId)
{
$topic = $topicRepository->findOrFail($topicId);
$post = $postRepository->findOrFail($postId);
}
instead of:
// Topic is a instance of Eloquent model
public function index(Topic $topic, $post Post)
{
//
}
Thank you in advance for all opinions and tips.
Aucun commentaire:
Enregistrer un commentaire