从Laravel 4中的事务中返回数据

时间:2013-06-18 20:12:08

标签: php closures laravel laravel-4

我有以下代码片段,我似乎无法使其正常工作。

$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');
}

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

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

我不得不最终做以下几种解决方法。

$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');
}

在Closure外部创建了对象$orderObj,并通过引用事务使其成为变量,以便在闭包函数之外使用它。这可以更简单吗?或者这是使用它的方式吗?

1 个答案:

答案 0 :(得分:11)

您可以在以下变量中分配事务闭包的返回值:

$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来返回。