2017-08-16 65 views
0

我使用Fat Free Framework ORM映射器功能來插入從客戶端傳遞到數組中的一組記錄。 Mapper函數具有回調函數,用於傳遞一組鍵和映射器對象。Fat-Free-Framework/F3在映射器回調中訪問配置單元變量

我希望能夠遍歷記錄,並使用映射器逐一插入記錄,將插入的記錄的id存儲在數組((result'ray))中,這是在父函數的F3配置單元中設置的:

function myFunction (\Base $f3, $params) { 

    // array of records to insert 
    $mappedArray = json_decode($f3->get('BODY'), true); 

    $f3->set('mapper', new mapper($db,'mytable')); 
    $mapper = $f3->get('mapper'); 

    // create an array in the hive to store the results of the inserts 
    $f3->set('resultsArray', array()); 

    // set mapper callbacks 
    $mapper->aftersave(function($self,$pkeys){ 
     // update the resultsArray in the hive? 
    }); 

    $recordsInArray = count($mappedArray); 

    // loop through the array of objects 
    for ($loop = 0; $loop<$recordsInArray; $loop++){ 

     $newRecord = $mappedArray[$loop];    

     try{ 
      // clear the mapper down 
      $mapper->reset(); 
      // set the array in the hive 
      $f3->set('data', $newRecord); 
      $mapper->copyFrom('data');  
      $mapper->save(); 

     } catch(\PDOException $e) { 
      // do something 
      exit; 
     } 
    }   

    echo "done"; 
} 

是否有方法可以訪問我在aftersave回調中配置的resultsArray變量?

感謝 馬特

回答

0

你確定你需要做的所有這些事情,實現你想要什麼? 爲了能夠存儲插入記錄的ID,並把它在F3的蜂巢,我會做到以下幾點:

<?php 
function myFunction (\Base $f3, $params) { 
    // array of records to insert 
    $mappedArray = json_decode($f3->get('BODY'), true); 
    //mapper (no need to put it into hive): 
    $mapper = new mapper($db,'mytable'); 
    // array with IDs: 
    $resultsArray = []; 
    // loop through the array of objects 
    for ($loop = 0; $loop<count($mappedArray); $loop++){ 

     try{ 
      // clear the mapper down 
      $mapper->reset(); 
      // map the content (no need to put it in the hive): 
      $mapper->copyFrom($mappedArray[$loop]); 
      // insert new record: 
      $mapper->save(); 
      // get the ID of the inserted record and put it in the array: 
      $resultsArray[] = $mapper->_id; 
     } catch(\PDOException $e) { 
      // do something 
      exit; 
     } 
    } 
    // put the array of IDs in the hive: 
    $f3->set("newIDs", $resultsArray); 
} 
0

您可以在aftersave處理程序中使用PHP訪問蜂房use功能:

function myFunction (\Base $f3, $params) { 
    // ... 
    $mapper->aftersave(function($self,$pkeys) use($f3) { 
     $f3->get('resultsArray'); 
    }); 
}