tags:

views:

33

answers:

4

i have written a php code that will make use of one xml feed. This feed is used by about 12 functions for various calculations.So in each function i use simplexml_load_file to load the file. Several functions are called in the same page to display variuos results depending on the variables passed. I would like to know is there a way that i can load the xml feed once so it can be used by all the functions do all the calculation depending of the variables passed, rather than loading the file 5 or 6 times on each page?

A: 
  1. Use a singleton and place the XML as a member property, that will work on the same request. Whenever anyone needs to access the XML, they call:

    $xml = singleton::getXML();

  2. If you want to persist something across a number of requests, your best bet is to stick in some cache layer like memcache or the database.

  3. Make the $xml global and process it at the start of the request.

Mr-sk
A: 
$xmlfeed = file_get_contents("http://website.com/xml.xml");

doSomeFeedMagic($xmlfeed);

doSomeMoreMagic($xmlfeed);

Where the functions are:

function doSomeFeedMagic($feed){

   // do magic here

}


function doSomeMoreMagic($feed){

   // do magic here

}

Load the feed before you call your functions then pass it to the function as a variable.

citricsquid
A: 

You could build a (static) class, containing all the functions and the values from the xml file.

class Calculations {

     private static $_xmlData;

     static function loadXml() {
         // load xml file and save data in self::$_xmlData
     }


     static function calculation01() {
          // calculate using self::$_xmlData
     }

}

If you need the same structure with different data, just don't make the function static.

PvB
+1  A: 

If your functions are very separate, you can just cache it in a function. For instance, instead of loading the file manually, you'd call load_xml() and it would cache it for you. That also means that any changes would stick to the cache. If you want a copy of it you'd have to clone it or something.

function load_xml($filename)
{
    static $cache = array();

    if (!isset($cache[$filename]))
    {
        $cache[$filename] = simplexml_load_file($filename);
    }

    return $cache[$filename];
}

Otherwise, you could be better off grouping your feed processing into a class and cache the original document as an object var.

class feed_processor
{
    protected $feed;

    public function __construct($filename)
    {
        $this->feed = simplexml_load_file($filename);
    }

    public do_some_stuff()
    {
        $this->feed->addChild('foo', 'bar');
    }
}
Josh Davis