问题描述
我刚刚开始在Laravel 5.1中使用Jobs,并且想知道从Job返回数据是否是一个好习惯?我还没有看到任何示例,但这是一个场景.可以说它是用户之间的内部消息系统:
I'm just starting to use Jobs in Laravel 5.1 and am wondering if it's a good practice to return data from a Job? I haven't seen any examples of that, but here's a scenario. Lets say its an internal Messaging System between Users:
// Controller Method
public function store(Request $request)
{
if (!$this->messageValidator->isValid($request->all())) {
return redirect()->back()->withInput()->withErrors($this->messageValidator->getErrors());
}
$this->dispatchFrom(PostMessage::class, $request, [ 'user' => Auth::user() ]);
return redirect('messages');
}
因此,工作将获取请求数据和用户,并执行多项任务
So the Job will take the request data and the User, and will perform several tasks
// In the PostMessage Job
public function handle( // dependencies here)
{
// Create a new Thread
// Add Message to the Database
// Store Recipients of Message in the Database
// Send email notifications to all involced
return $message_id;
}
在handle()方法的末尾,我返回了$ message_id,以便可以将其用于控制器中的重定向:
At the end of the handle() method, I returned the $message_id so I can use it for a redirect in the controller:
return view('messages.show', $message_id);
这是可以接受的做法,还是乔布斯打算以更孤立的方式执行任务?
Is this an acceptable practice, or are Jobs meant to perform tasks in a more isolated manner?
或者也许不是乔布斯的好用吗?
Or is perhaps not a good use of Jobs?
推荐答案
通常,乔布斯用于您可能要排队等待在后台运行(异步)的事物,因此从它们中接收返回值有点奇怪.
Normally Jobs are used for things you might want to queue to run in the background (asynchronously), so it's a bit odd to receive a return value from them.
我会将数据库保存移到其他地方,仅将作业用于电子邮件通知:
I would move the database saving elsewhere, and only use the Job for email notifications:
// Controller Method
public function store(Request $request, MessageGuru $messageGuru)
{
if (!$this->messageValidator->isValid($request->all())) {
return redirect()->back()->withInput()
->withErrors($this->messageValidator->getErrors());
}
$messageId = $messageGuru->store($request->all());
$this->dispatchFrom(PostMessage::class, $request, [ 'user' => Auth::user() ]);
return view('messages.show', $messageId);
}
// MessageGuru
class MessageGuru {
public function store ($input) {
// Add Message to the Database
// Store Recipients of Message in the Database
}
}
// In the PostMessage Job
public function handle()
{
// Send email notifications to all involved
}
我确实检查了Laravel源代码,如果未将作业排队,则确实会返回该作业的返回值,但是以这种方式使用Jobs将限制您稍后将其重构为排队的作业.
I did check the Laravel source code, and the return value from the job is indeed returned if the job isn't queued, but using Jobs that way would restrict you from refactoring it into a queued job later.
这篇关于Laravel 5.1-从乔布斯返回数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!