We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

How to save a sql resultset and refer back to it?

I'm currently working on a system where a form is completed and upon completion the database is queried to get a set of figures and use the answers from the form to make calculations with them.

Once the calculation has been saved it must refer back to the same SQL figures when the form was originally completed, it must refer back to these original figures for a specified amount of time (lets say a month) so if the figures are updated within that month it will ignore the changes and use what was originally retreived.

Any ideas on the best way to do this?

You can use the phalcon cache classes:

https://docs.phalcon.io/en/latest/reference/models-cache.html

Essentially what you can do is this:

$di->set('modelsCache', function() {
    $frontcache = new Phalcon\Cache\Frontend\Data(array(
        "lifetime" => 172800 //two days
    ));
    $cache = new Phalcon\Cache\Backend\File($frontcache, array(
        "cacheDir" => "../app/cache/"
    ));

    return $cache;
});

//Then you can do
$products = Products::find(array(
    "cache" => array(
       "key" => "my-cache", 

        //You can overwrite the lifetime defined in modelsCache here
        //"lifetime" => 300
    )
));

//Products::find will use the cache until 2 days (in my case), then will query the database again

Hi Max and thanks for your post.

I know there is models cache but this won't accomodate what I'm trying to do.

To clear things up a bit, say I have 3 database tables that contain different prices for different selections on a form, the form is saved as an entry in the database.

A week later the prices increase, I then amend the previously saved form, when this form is re-saved it shouldn't use the NEW prices it should use the OLD prices however any NEW completed forms will use the NEW prices a NEW form is saved it is saved with the NEW prices and so on.

If you can tell apart new and old forms. you can use or not use the cache simpy by omitting the key cache:


//Old forms
$products = Products::find(array(
    "cache" => array(
       "key" => "my-cache", 
    )
));

//New forms
$products = Products::find();