3

我有以下代码片段,我似乎无法让它工作。

$paymentGatewayTransaction = $this->processTransaction($data);
DB::connection('new_db')->transaction(function () use ($paymentGatewayTransaction) {
    //Performing all DB transactions here to insert Order Information.
    if ($paymentGatewayTransaction['Status'] == "APPROVED")
        return Response::json(array('Status' => 'Success'), '200'); else
        return Response::json(array('Status' => 'Error'), '200');
});

function processTransaction($data) {
    //Process Gateway Transaction
    if ($gatewayWasSuccessfull)
        return array('Status' => 'APPROVED'); else
        return array('Status' => 'DECLINED');
}

线上的返回 Response::json()5似乎7根本没有任何效果。响应永远不会到达浏览器。

如果我将 if 条件从行移动48闭包函数之外,它可以正常工作。

作为一种解决方法,我最终不得不执行以下操作。

$paymentGatewayTransaction = $this->processTransaction($data);
$orderObj = "";
DB::connection('new_db')->transaction(function () use ($paymentGatewayTransaction, &$orderObj) {
    //Performing all DB transactions here to insert Order Information.
    // **$orderObj is set here**
});

if ($paymentGatewayTransaction['Status'] == "APPROVED")
    return Response::json(array('Status' => 'Success', 'Order' => $orderObj->id), '200'); else
    return Response::json(array('Status' => 'Error'), '200');

function processTransaction($data) {
    //Process Gateway Transaction
    if ($gatewayWasSuccessfull)
        return array('Status' => 'APPROVED'); else
        return array('Status' => 'DECLINED');
}

在闭包之外创建对象$orderObj,并通过引用事务将其作为变量,以便在闭包函数之外使用它。这可以更简单还是这是使用它的方法?

4

1 回答 1

14

您可以将事务关闭的返回值分配到如下变量中:

$paymentGatewayTransaction = $this->processTransaction($data);
$var = DB::connection('new_db')->transaction(function () use ($paymentGatewayTransaction) {
    //Performing all DB transactions here to insert Order Information.
    if ($paymentGatewayTransaction['Status'] == "APPROVED")
        return Response::json(array('Status' => 'Success'), '200'); else
        return Response::json(array('Status' => 'Error'), '200');
});
return $var;

然后你可以使用 $var 返回。

于 2013-06-19T08:57:54.777 回答