Skip to content
Advertisement

Magento: Retrieving uncached system configuration values

I have a script that sends order data to a 3rd party system via a RESTful web service. This system demands that a unique ID is sent with each request, which is autoincremented from the next.

I’ve implemented this by adding a variable for this in Magento’s core_config_data table, and as part of my code the function below is called to get the next value for the ID, incrementing it for the next request.

class MyProject
{
    public function getNextApiId() {
        // Get the next ID.
        $id = Mage::getStoreConfig('myproject/next_api_id');

        // Increment the stored value for next time.
        $nextId = $id + 1; // change $id++ by $id + 1 otherwise the result of $nextId = $id - 1;
        Mage::getModel('core/config')->saveConfig('myproject/next_api_id',$nextId);

        // Refresh the config.
        Mage::getConfig()->cleanCache();
        Mage::getConfig()->reinit();

        // Return the ID.
        return $id;
    }
}

If I send one request with my script, this works fine – the value is incremented and the next ID is used for the next execution of the script.

However, the value appears to be cached if I’m processing multiple requests in a loop within the same script execution. The code below should illustrate the general flow, though I’ve reduced it for brevity:

function sendRequest($item) {
    $apiId = $MyProject->getNextApiId();

    // Build and send request body
}

foreach($items as $item) {
    sendRequest($item);
}

This would result in the initial ID number being used for all $items.

The cleanCache() and reinit() attempts to refresh the config cache do not seem to work at all. Any ideas on how to stop the value from being cached?

Advertisement

Answer

Cache must be cleaned in a different way, you have to reset the cache of the store and init it again cause of the loop. If you didn’t have a loop, it will be cleaned also but it needs a second url request of the shop which will init the cache.

Try this instead:

function getNextApiId() {
    // Get the next ID.
    $id = Mage::getStoreConfig('myproject/next_api_id');

    // Increment the stored value for next time.
    $nextId = $id + 1;

    Mage::getConfig()->saveConfig('myproject/next_api_id',$nextId);

    // Refresh the config.
    Mage::app()->getStore()->resetConfig();

    // Return the ID.
    return $id;
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement