2015-04-03 74 views
0

可以说我有UserControler处理用户的创建删除等和评论conntroler一个处理意见的添加删除modyfing等如何设计控制器的通信

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

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

回答

1

您可以使用这些方法总是会得到验证的用户信息:

//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', '[email protected]'); 

然后你就可以创建一个按钮(我将在这里使用bootstrap和hipotetical ID)指向:

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

在你的评论控制器,你可以有mething这样的:

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')); 
} 
+0

我可以使用Request类请求任何类的对象吗? – zarcel 2015-04-03 14:50:33

+0

No.请求只会让您提出请求的用户。如果您需要另一个雄辩课程,您可以使用让我们说$ comment = App \ Comment :: find($ id)。当然,考虑到你的班级在应用程序文件夹的根目录下。如果您将其设置在子文件夹中,您将不得不使用命名空间。 – 2015-04-03 15:04:34

0

立即回答将是CommentController,这是应该添加/删除/编辑评论的控制器。

其他任何人都可以添加/删除/编辑用户以外的评论吗?如果是,他们是否会进入相同的业务/域对象?

可以说,如果您有用户评论和客户评论有单独的业务/域评论对象,在这种情况下,您可能有单独的UserCommentsController和CustomerCommentsController。

而@Arthur Samarcos建议您可以获取用户信息。

0

在这样的情况下,每个评论仅属于一个用户,我设置了在评论控制器,因为用户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'); 
    } 
} 

有这种方法的几个好处。正如我之前所说,它使您的代码可重用并易于理解。你需要做的只是在你需要的地方将资源库注入你的控制器。二是它变得更可测试。