Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Magento Event Dispatching/Observing/Modifying Dispatched Objects

Tags:

php

magento

I am trying to work through a problem, but am not having any success. I need to send down some additional information with the Magento API order info request. Unfortunately, Magento doesn't seem to have any events tied to this, so I overwrote that class and to dispatch an event. That is all well and fine, as I modify the $result array, with the new information. However the part that is not fine is that the array that was modified never shows back up in the original dispatching code.

Here is the dispatch:

class Company_Module_Model_Order_Api extends Mage_Sales_Model_Order_Api {

    public function info($orderIncrementId) {
        $result = parent::info($orderIncrementId);
        $order = $this->_initOrder($orderIncrementId);

        Mage::dispatchEvent("company_api_order_info_add", 
                    array('result' => &$result, 'order' => &$order));
    // - I've tried with and without the ampersand

        Mage::log($result['affiliate_text']); // Debugging

        return $result;
    }
}

Here is the watcher code:

class Company_Other_Model_Api
{
    public function hookToSetAffiliate ($observer) {
        $result = $observer->getResult();
        $order = $observer->getOrder();

        if ($order->getAffiliateCode()) {
            $affiliate = Mage::getModel('affiliates/info')
                    ->load($order->getAffiliateCode());
            if (is_object($affiliate))
                $result['affiliate_text'] = $affiliate->getCode();
            }

            Mage::log($result['affiliate_text']); // Shows up here

            return $observer;
        }
    }
}

Do you have any ideas why $result is not coming in properly? In the hook, it show up properly, however, 'affiliate_text' is not visible when the next line of the dispatching method occurs.

Thanks,

JMax

like image 284
Joseph at SwiftOtter Avatar asked Jun 25 '26 21:06

Joseph at SwiftOtter


1 Answers

I would suggest you take the same route that Magento does.

// Wrap array in an object
$result = new Varien_Object($result);

// Dispatch - No need for & as $result and $order are both objects and passed by ref
Mage::dispatchEvent("company_api_order_info_add", array('result'=>$result, 'order'=>$order));

// Unwrap array from object
$result = $result->getData();

Varien_Object will still allow array access, so your listener code shouldn't have to change at all.

like image 84
Lee Saferite Avatar answered Jun 27 '26 11:06

Lee Saferite



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!