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 auto delete model caches

Hello,

I'm trying to use Model Cache. However I wish to delete related cache when I create new record or update record on related model.

This was works

<?php

// Get products without caching
$products = Products::find();

// Just cache the resultset. The cache will expire in 1 hour (3600 seconds)
$products = Products::find(array(
    "cache" => array("key" => "my-cache")
));

// Cache the resultset for only for 5 minutes
$products = Products::find(array(
    "cache" => array("key" => "my-cache", "lifetime" => 300)
));

// Using a custom cache
$products = Products::find(array("cache" => $myCache));

However when I create new product. Cache still contains old recordset. So I want to delete that cache after creating new product (and after updating or deleting records too ).

My Best Regards



2.3k
Accepted
answer

You should use user define bahaviors in model (clear cache after any save).

https://docs.phalcon.io/en/latest/reference/models.html#creating-your-own-behaviors



11.9k

Ok thanks, for help.

However I'm still looking for finding (and or deleting) orm caches by using init keys.

something like

<?php
define('DB_READ_KEY','my-cache');

$products = Products::find(array(
    "cache" => array("key" => DB_READ_KEY)
));

Products::deleteCache(DB_READ_KEY);

My Best Regards



11.9k

Ok I found solution here,

https://forum.phalcon.io/discussion/3498/delete-cache-manually

Combining both of them will solve my problem best regards.

edited May '15

If you want do this in static context you have two ways:

  1. Reinitialize cache backend and frontend in method like this

  2. Pass dependency injector and use cache object defined in it in yours method.