Ray
Ray

Reputation: 1145

CakePHP 3: Set cache duration in Controller when writing

I am using CakePHP 3 in my project. I am still learning new things as I go. Today I had a requirement to use CakePHP cache to cache data that I retrieve from the database. Every time I load a page that returns data from the database, takes around 30 to 40 seconds.

So I went ahead and configured cache in my controller, which significantly improved page loading from 30 sec to less then 4 seconds.

Now, what I want to do is set duration of the cache to clear itself after 1 hour to refresh new data that is stored in the database.

This is my code that does the caching:

if (!($custstoredata = Cache::read('custstoredata'))) {
  # Code logic
  Cache::write('custstoredata', $customers);
  $this->set('data',$customers);
} else {
  $this->set('data', Cache::read('custstoredata'));
}

After doing some research online, I found that I can use Cache::set to configure duration so I went a ahead and added Cache::set(array('duration' => '+1 hour')); in my if statement, but when I load the page in browser, I get this error:

Error: Call to undefined method Cake\Cache\Cache::set()

I am not sure what is the right way to set caching duration in controller real time when cache is written to a file.

Upvotes: 0

Views: 1836

Answers (1)

Ray
Ray

Reputation: 1145

I think I answered my own question.

I added below cache config in app.php file:

'reports_seconds' => [
            'className' => 'File',
            'path' => CACHE,
            'serialize' => true,
            'duration' => '+60 seconds',
        ]

Once I added above code, I modified my if statement with below code that fixed the problem.

if (!($custstoredata = Cache::read('custstoredata'))) {
    # Code logic
    Cache::write('custstoredata', $customers, $config = 'reports_seconds');
    $this->set('data',$customers);
} else {
    $this->set('data', Cache::read('custstoredata'));
}

Upvotes: 2

Related Questions