可以說我有UserControler處理用戶的創建刪除等和評論conntroler一個處理意見的添加刪除modyfing等如何設計控制器的通信
如果我的用戶要添加評論? userController是否應該有addComment方法?或者我應該在commentsController中處理這個問題(如果是的話,我如何傳遞用戶數據)? 也許我根本不需要commentsController?
如何根據MVC(我正在使用laravel)正確設計它?
可以說我有UserControler處理用戶的創建刪除等和評論conntroler一個處理意見的添加刪除modyfing等如何設計控制器的通信
如果我的用戶要添加評論? userController是否應該有addComment方法?或者我應該在commentsController中處理這個問題(如果是的話,我如何傳遞用戶數據)? 也許我根本不需要commentsController?
如何根據MVC(我正在使用laravel)正確設計它?
您可以使用這些方法總是會得到驗證的用戶信息:
//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'));
}
立即回答將是CommentController,這是應該添加/刪除/編輯評論的控制器。
其他任何人都可以添加/刪除/編輯用戶以外的評論嗎?如果是,他們是否會進入相同的業務/域對象?
可以說,如果您有用戶評論和客戶評論有單獨的業務/域評論對象,在這種情況下,您可能有單獨的UserCommentsController和CustomerCommentsController。
而@Arthur Samarcos建議您可以獲取用戶信息。
在這樣的情況下,每個評論僅屬於一個用戶,我設置了在評論控制器,因爲用戶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');
}
}
有這種方法的幾個好處。正如我之前所說,它使您的代碼可重用並易於理解。你需要做的只是在你需要的地方將資源庫注入你的控制器。二是它變得更可測試。
我可以使用Request類請求任何類的對象嗎? – zarcel 2015-04-03 14:50:33
No.請求只會讓您提出請求的用戶。如果您需要另一個雄辯課程,您可以使用讓我們說$ comment = App \ Comment :: find($ id)。當然,考慮到你的班級在應用程序文件夾的根目錄下。如果您將其設置在子文件夾中,您將不得不使用命名空間。 – 2015-04-03 15:04:34