Get new empty item on model method
-
16-10-2019 - |
Question
Collections provide a handy means of getting a blank model - e.g.:
$quote->getItemsCollection()->getNewEmptyItem();
Is there any means of doing this from an existing model without having to call for the collection - in other words directly from the instance? Something like this:
$product = Mage::getModel('catalog/product')->load(43);
$productNew = $product->getNewEmptyItem();
I do realize I could call getCollection()
on the product first - not sure if this has some overhead.
Edit:
Obviously $product = Mage::getModel('catalog/product');
produces the desired result. Obviously. What I'm looking for is a means of getting a blank object without reinstantiating the model.
Perhaps I just need to switch to using singletons to ease my mind.
Solution
You can use reset();
Mage::getModel('catalog/product')->load(1)->reset();
that calls _clearData, if you check in the Mage_Catalog_Model_Product you can see that this function resets all variables.
OTHER TIPS
The reset()
method is available for Mage_Catalog_Model_Product
but as a whole, this isn't available.
You could add a method like this:
public function reset() {
return new self();
}
However, you cannot then call:
$modelInstance->reset();
You would have to call:
$modelInstance = $modelInstance->reset();
Because of this, in my opinion, having your own reset()
method is going to lead to misuse, and/or may confuse other developers. You are better off doing something like this:
$modelInstance = new $modelInstance;
Does this not work via the clearInstance
function on Mage_Core_Model_Abstract
. This seems to clear references and data plus it also fires an event:
Mage::dispatchEvent($this->_eventPrefix.'_clear', $this->_getEventData());
Maybe I am missing something here though.