1

I have a query regarding magento 1.6.

I have a number of objects that I am creating, calling a method on and saving to the database with the Mage_Core_Model_Resource_Transaction transaction model.

The method now requires the primary key value of the object, which obviously isn't going to be available until after the object has been saved to the database.

Can I just loop through the created objects after they've been saved to the database? Instead, do I need to use the transaction's addCommitCallback method?

In other words, can I do:

$collection = [];
$transaction = Mage::getModel('core/resource_transaction');
for ($i = 0; $i <= 10; $i++) {
    $obj = new ObjectFoo;
    $transaction->addObject($obj);
    $collection[] = $obj;
}
$transaction->save();
foreach($collection as $collected) {
    $this->doSomething($collected);
}

(And assume that each $collected item will now have a valid id value)

Or do I need to use something like:

$transaction->addCommitCallback(array($obj, 'doSomething'));

One thing that I have noticed with addCommitCallback is that you can not specify any parameters for the callback, which is rather... restrictive.

2

So to explain what is going on you need to understand that

$transaction = Mage::getModel('core/resource_transaction');
for ($i = 0; $i <= 2; $i++) {
    $obj = new ObjectFoo;
    $transaction->addObject($obj);
    $transaction->addCommitCallback(array($obj, 'doSomething'));
}
$transaction->save();

Is equal to

//start transaction
$obj0 = new ObjectFoo;
$obj0->save();
$obj1 = new ObjectFoo;
$obj1->save();
$obj2 = new ObjectFoo;
$obj3->save();
//commit
$obj0->doSomething();
$obj1->doSomething();
$obj2->doSomething();

So answering your question it is not necessary to use addCommitCallback and you can easily use saved objects after $transaction->save();. They will have ids.

Especially in your case it is not possible to use addCommitCallback instead of

foreach($collection as $collected) {
    $this->doSomething($collected);
}

because you cann't pass parameters of callback function into addCommitCallback.

| improve this answer | |
0

if you use the for loop after transaction save, you will lost consistent transaction. If anything throws error in the for loop, everything saved in the transaction resource model won't be roll back. So you want to use $transaction->addCommitCallback(array($obj, 'doSomething');

if you want to pass parameters, extend the resource transaction model.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.