如何设计控制器通信

How to design controllers communication

假设我有处理用户创建删除等的 UserControler 和处理评论添加删除修改等的评论控制器

如果我的用户想要添加评论怎么办? userController 应该有 addComment 方法吗?或者我应该在 commentsController 中处理这个问题(如果是这样,我该如何传递用户数据)? 也许我根本不需要 commentsController?

如何根据MVC正确设计(我使用的是laravel)?

直接答案是 CommentController ,这是应该 add/delete/edit 评论的控制器。

除了用户之外还有其他人 add/delete/edit 可以发表评论吗?如果是,它们会进入同一个 business/domain 对象吗?

假设您有用户评论和客户评论有单独的 Business/Domain 评论对象,在这种情况下您可能有单独的 UserCommentsController 和 CustomerCommentsController。

正如@Arthur Samarcos 建议的那样,您可以获得用户信息。

您始终可以使用这些方法获取经过身份验证的用户信息:

//Will return the authenticated User object via Guard Facade.
$user = \Auth::user(); 

//Will return the User Object that generated the resquest via Request facade.
$user = \Request::user();

如果您将路线设置成这样:

Route::get('posts/{posts}/comments/create', 'CommentsController@create');

然后您可以创建一个按钮(我将在此处使用 bootstrap 和 hipotetical id)指向:

<a href="posts/9/comments/create" class="btn btn-primary">Create</a>

在你的 CommentsController 上你可以有这样的东西:

public function create($post_id)
{
   $user = .... (use one of the methods above);
   $post = ... (get the post to be commented, if thats the case)
   ... Call the create comment function
   return redirect(url('posts/9'));
}

在这种情况下,每条评论只属于一个用户,我会在评论控制器中进行设置,因为用户 ID 实际上只是该评论的另一个属性。

此外,我发现最好将此逻辑抽象到存储库中,以防您最终需要从另一个控制器或应用程序中的其他位置创建评论。也许如果用户采取某些行动,您希望在采取这些行动时自动生成评论。存储库可能如下所示...

class CommentRepository {

    protected $comment;

    public function __construct(Comment $comment)
    {
        $this->comment = $comment;
    }

    public function newComment($user_id, $content)
    {
        $comment = $this->comment->newInstance();
        $comment->user_id = $user_id;
        $comment->content = $content;
        $comment->save();
        return $comment;
    }
}

然后你将该存储库注入你的控制器,它看起来像这样...

class CommentController extends BaseController {

    protected $cr;

    public function __construct(CommentRepository $cr)
    {
        $this->cr = $cr;
    }

    public function create()
    {
        $comment = $this->cr->newComment(Auth::user()->id, Input::get('content'));

        return Redirect::route('comments.index');
    }
}

这种方法有一些好处。一个正如我之前所说,它使您的代码可重用且易于理解。您需要做的就是将存储库注入到您需要的控制器中。二是它变得更容易测试。