2016-07-03 10 views
0

は、私がのForeachループ - foreachループですべてまたは何も

foreach($items as $item) 
{ 

    // charge a user for purchasing an item - IS BEING DONE THROUGH AN API CALL WITH STRIPE 
    // ie: \Stripe\Charge::create(...); 

    // save some info to a database 
    // using Laravel for this project so this is within a DB::transaction(...); 


    // send a notification email to the buyer 
    // Emails are being queued to avoid slowing down the request 
    // ie: Mail::queue(...); 
} 

私はオールオアナッシングな状況が発生したい、次のやってみたかったと言います。例えば、反復中にエラーが発生した場合、アイテムのうちの1アイテムは請求されず、情報はデータベースに保存されず、購入者は通知電子メールを受け取らない。ただし、foreachループが各アイテムを正常に反復してから、ユーザーに請求し、情報をデータベースに保存し、通知電子メールを送信します。これはどうすればいいですか?

+0

すべての商品について同じバイヤーに通知されますか? – Terminus

+0

あなたはどんなDBMSを使用していますか? –

+0

これはトランザクションとして処理する必要があると思います。 –

答えて

1

私はトランザクションを使用し、買い手に最後に通知することをお勧めします。

のMysqli例:

$dbConn->begin_transaction(); 

try{ 

    foreach($ítems as $item){ 
     //Whatever you are going to do 
    } 

    if($dbConn->commit()){ 

    //Notify buyer about all the transactions, the user doesn't receives the notification unless the commit was succesful 

    } 

catch(Exception ex){ 
    $dbConn->rollback(); 
} 

また、あなたが、私はただ、トランザクションの使用に焦点を当てたかったmysqliの関数の戻り値を、確認することができます。

+0

取引を始めるのはいいですが、通知メールについてはどうしますか? – Terminus

+0

'$ dbConn-> commit()'の結果を確認してください –

+0

しかし、2回目のコミットに失敗した場合、OPは最初のメールを外出させたくありません。私はトランザクションで、あなたはOPが私の答えよりも必要なものをキャプチャすると思いますが、あなたは電子メールを説明する必要があります。 – Terminus

0

各項目を別々に請求している場合と同様に、@ Terminusの詳細を追加する必要があります。しかし、必要に応じて、ループの終わりまで実行することなく、ループ中にdbクエリを構築することができます。その後、(インプリメンテーションごとに)請求をロールバックしてから、必要に応じて1つ以上の電子メールを送信する必要があります。

0

あなたは、配列内の項目の何を数えていないし、それを動作させるためにいくつかの変更を行うことができます。

$result = count($items); 
$c = 0; 
foreach($items as $item) 
{ 
// charge a user for purchasing an item -- instead add it to a buffer as total 
//amount. 
// save some info to a database ---instead prepare your db statements here 
// send a notification email to the buyer.--this could be sent out for all the 
//items in the order together outside the loop instead of inside the loop. 
$c = $c + 1; 
} 
if($c == $cc) 
{ 
//execute your prepared statements here..and also the other email and charging stuff. 
} 
else{ 
//Error code. 
} 
+0

ここでは、ループ内のアイテムが同じバイヤーに属すると仮定しています。 – Siddhesh

0

あなたは選択肢を持っています。

私が考えることができる最も簡単な方法は、配列上のループです。条件を最初にチェックし、最初のスルースルーで問題がない場合にのみ2番目の条件を確認します。

$isGoodToGo = true; 
foreach($items as $item) { 
    if (conditon met) { 
    $isGoodToGo = false; 
    break; // stop iterating over the array cause condition is met 
    } 
} 

if ($isGoodToGo) { 
    foreach($items as $item) { 
    // charge a user for purchasing an item 
    // save some info to a database 
    // send a notification email to the buyer 
    } 
}