gpt4 book ai didi

php - 在存储库模式中保存关系的好方法是什么?

转载 作者:搜寻专家 更新时间:2023-10-31 21:53:25 24 4
gpt4 key购买 nike

在保存数据时,我对使用存储库模式感到困惑。我写了讨论板,所以当用户创建一个新线程时,我需要保存许多对象(关系)。基本上我需要:

  1. topics 表中创建新记录
  2. posts 表中创建新记录
  3. 分配帖子的附件
  4. 将用户 ID 添加到 subscribers 表(这样他/她就可以收到有关新回复的通知)

它可能看起来像这样:

$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 ...

但我感觉我做错了。我不应该在我的存储库中创建新方法来创建新线程(将新记录添加到 topicsposts 表)并保持我的 Controller 清洁吗?

大概是这样的?

// 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

所以问题是:

1) 在存储库模式中保存关系的好方法是什么?

存储库模式应该处理保存所有关系吗?

2) 路由模型绑定(bind)和存储库模式

路由模型绑定(bind)是 Laravel 的一大特色。它不会破坏存储库模式规则吗?我的意思是:我们应该写:

public function index($topicId, $postId)
{
$topic = $topicRepository->findOrFail($topicId);
$post = $postRepository->findOrFail($postId);
}

代替:

// Topic is a instance of Eloquent model
public function index(Topic $topic, Post $post)
{
//
}

3) 如何在一个 Controller 操作中创建或更新论坛线程?

为了 DRY,我需要创建一个可以处理创建新线程或更新现有线程的 Controller 操作。如何在 Laravel 中使用存储库模式来做到这一点?

这是一个好方法吗?

public function save($topicId, $postId, Request $request)
{
// ...
$topicRepository->updateOrCreate($topicId, $postId, $request->all();
}

提前感谢您的所有意见和提示。

最佳答案

对于第 2 部分,您可以创建自定义中间件以通过您的存储库执行您自己的模型绑定(bind)。

<?php

namespace App\Http\Middleware;

use Closure;

class CustomBindingMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$topicId = $request->route('topic');

if ($topicId) {
//Get $topicRepository

$topic = $topicRepository->findOrFail($topicId)
$request->route()->setParameter('topic', $topic);
}

return $next($request);
}
}

关于php - 在存储库模式中保存关系的好方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36711227/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com