函数逻辑在随机次数的尝试后工作


Function logic works after random number of attempts

我不明白为什么removeAction函数在随机次数的尝试后仍能工作。有时它是第一次起作用,而其他时候我必须反复点击(4或5次),直到它起作用。

我知道它有效,因为产品id已从用户购物车中删除。

我不确定这是否有帮助,但我对照函数的microtime()(即float(0.0148420333862))检查了max_execution_time(即30)。

当我转储$quantity$cart时,我始终看到正确的产品id。

removeAction function:

    /**
     * Removes a 'product' from the cart
     *
     * @Route("/{id}/remove", name="product_remove")
     * @METHOD("GET")
     * @Template()
     */
    public function removeAction(Request $request, $id) {
       // $time = microtime(true);
        $em = $this->getDoctrine()->getManager();
        $product = $em->getRepository('ShopBundle:Product')->find($id);
        $cart = $em->getRepository('ShopBundle:UserCart')->findOneBy(['user' => $this->getUser(), 'submitted' => false]);
        $quantity = $em->getRepository('ShopBundle:Quantity')->findOneBy(['product' => $product->getId()]);
                                                //get product id from the cart and then remove it
    // product gets removed but only after a random # of click on the remove button...
//ini_get('max_execution_time');
//var_dump(ini_get('max_execution_time'));
        // dump($quantity);
        // dump($cart);

        $em->remove($quantity);
        $em->flush();
        $this->addFlash('notice', 'The product: '.$product->getName().' was removed!');
        //var_dump(microtime(true) - $time); die;
        return $this->redirectToRoute('product_showCart');
    }

这里有一个例子,我对您的代码做了一些假设,但这大致是我期望的工作方式,而且简单得多。

您应该能够检查购物车,找到匹配的项目并以这种方式删除它,如果没有,那么您可能应该重构购物车的构建方式。

我想,你的原始代码在一系列点击后工作的原因是它从所有的购物车中删除了产品,直到它到达你的购物车,这显然是不理想的。

/**
 * Removes a 'product' from the cart
 *
 * @Route("/{id}/remove", name="product_remove")
 * @METHOD("GET")
 * @Template()
 */
public function removeAction(Request $request, $id) {
    $em = $this->getDoctrine()->getManager();
    $cart = $em->getRepository('ShopBundle:UserCart')->findOneBy(['user' => $this->getUser(), 'submitted' => false]);
    // Surely you must have some sort of cart->product or cart -> cartitem -> product relation here - I make some assumptions but what you
    // do should ideally work similar to this.
    foreach ($cart->getItems() as $item) {
        if ($item->getProduct()->getId() == $id) {
            $em->remove($item);
            $em->flush();
            $this->addFlash('notice', 'The product was removed!');
            return $this->redirectToRoute('product_showCart');
        }
    }
    // here you could put some kind of error because you failed to remove the product        
}