Search code examples
phpzend-framework2zend-db

ZF2 TableGateway repeating values when loading from csv file


First of all, sorry for bad english.

I am trying to load several users from a csv list like this:

<?php
$handle = fopen ("teste.csv","r");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    $user = $this->getServiceLocator()->get('User');
    $user->exchangeArray(
        array( 'firsname'=>$data[0],
                'lastname'=>$data[1],
                'email'=>$data[2],
                'adress'=>$data[3],
                'phone'=>$data[4]
            )
        );
    $userTable = $this->getServiceLocator()->get('UserTable');
    $userTable->save($user);
}
fclose ($handle);
?>

But I don't know why it repeats the same values every time, as there's always the same values every line...

Looks like the service manager always clone the same object before saving..

Can anyone help?


Solution

  • Try to see if this makes a difference:

    $user = (clone) $this->getServiceLocator()->get('User');
    

    The service manager will only provide you with a new instance each time if you specifically tell it to

    http://framework.zend.com/manual/2.0/en/modules/zend.service-manager.quick-start.html
    

    Note the part about shared services. This would tell the service manager you want a new User object every time, then you will not need to clone the object as above

    'shared' => array(
            // Usually, you'll only indicate services that should _NOT_ be
            // shared -- i.e., ones where you want a different instance
            // every time.
            'User' => false,
        ),