Fat-Free-Framework / F3访问映射器回调中的hive变量

时间:2017-08-16 20:03:24

标签: fat-free-framework

我正在使用Fat Free Framework ORM Mapper功能来插入从数组中的客户端传递的一组记录。 Mapper函数对aftersave进行回调,后者传递一组键和映射器对象。

我希望能够循环遍历记录并使用映射器逐个插入记录,将插入记录的id存储在数组('resultsArray')中,该数组在父函数的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回调中的hive中设置的resultsArray变量?

由于 马特

2 个答案:

答案 0 :(得分: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);
}

答案 1 :(得分:0)

您可以使用php use功能访问aftersave处理程序中的配置单元:

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