[英]How to perform tasks avoiding the user being forced to wait the response?
在用户创建新产品后,在我的应用程序中,我会执行几个操作,例如更新几个表:统计信息,财务,使用情况,库存等。
现在用户必须等待我已完成所有步骤。 如果很多用户托盘同时进行,那么等待的时间要多得多,而且不太好。
我的计划是创建一个特殊的TASK_TABLE(product_id,time,task_id)然后在后台运行这个任务但是:
我怎么能在Symfony中做到这一点?
最好的方法是什么?
最好的方法是什么?
我不知道这是“最好”的方式,但处理这类案例的最常见方式( 基于提供的少数信息 )是:
NewProductEvent
,其中存储新的产品对象: NewProductListener
,其中处理“操作”执行的顺序,等等。 现在用户必须等待我已完成所有步骤。
为了避免这种情况,我们必须能够在响应已经提供给客户端之后“调度”我们的new_product_created
事件,并且我们可以使用服务标记 ,更具体地说是内核终止事件来执行此操作 。
但是如何存储产品数据以使其在kernel.terminate上可用?
我们去实现吧。
“事件”类:
use Symfony\Component\EventDispatcher\Event;
use YourApp\YourBundle\Entity\Product;
class NewProductEvent extends Event
{
const EVENT_NAME = 'new_product_created';
protected $product;
public function __construct(Product $newProduct)
{
$this->product = $newProduct;
}
public function getProduct()
{
return $this->product;
}
}
“听众”课程:
class NewProductListener
{
protected $product;
public function __construct()
{
# then you can inject all dependencies needed to perform your tasks
}
public function onNewProductCreated(Product $newProduct)
{
# here you keep in memory the product data!
$this->product = $newProduct->getProduct();
}
public function performTasks()
{
if ($this->product) {
# here you can put the logic to perform all needed tasks!
}
}
}
监听器“服务”定义:
<service id="new_product_listener"
class="YourApp\YourBundle\Event\NewProductListener">
<!-- you can inject in the listener, as argument, each service task you need -->
<!-- <argument type="service" id="financial_operation_service"/>-->
<!-- <argument type="service" id="usage_operation_service"/>-->
<tag name="kernel.event_listener" event="new_product_created" method="onNewProductCreated"/>
<tag name="kernel.event_listener" event="kernel.terminate" method="performTasks"/>
</service>
现在的实际例子( 我不评论代码,因为它是自我解释 ):
// presuming you are in a controller:
$dispatcher = $this->get('event_dispatcher');
$newProduct = //--- I don't know from where it will come.
$event = new NewProductEvent($newProduct);
$dispatcher->dispatch(NewProductEvent::EVENT_NAME, $event);
当你发送的NewProductEvent :: EVENT_NAME( new_product_created
),你将存储产品数据触发onNewProductCreated
的方法$product
中的变量NewProductListener
听众则可以在以后使用它kernel.terminate
事件被触发!
通过这种方式,Symfony将执行所需的任务( 在后台 )并且不会降低用户体验。
一些参考:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.