Last Updated:

Working with cache in OpenCart 3

Hello. We continue to explore OpenCart 3. So in the last article "Clearing the cache in OpenCart 3" we looked at how to clear and disable the cache from the admin panel. And in this article, let's dive into the bowels of OpenCart and learn how to manage the cache using the OpenCart 3 API.

 

We will experiment on the home page. The index method of the ControllerCommonHome controller is responsible for displaying the home page, which is located catalog/controller/common in the home.php file.

Let's check and add in the index method:

<?php

class ControllerCommonHome extends Controller {

public function index() {

var_dump('test');die;

And let's open the home page of our project.

OpenCart 3 4

It's cool.

Get data from the cache.

To retrieve data from the cache, OpenCart uses

$this->cache->get('<key>'))  

Let's check for this in our index method of the ControllerCommonHome controller to add the following code:

class ControllerCommonHome extends Controller {

public function index() {

var_dump($this->cache->get('test'));die;

Let's see what happens:

OpenCart 3 5

Returned false because we have nothing in the cache with the "test" key.

Write data to the cache.

To write data to the cache, use:

$this->cache->set('<key>','<value>');  

Let's write "This is the test value of the cache" in the cache with the key "test". And then let's derive this value:

<?php

class ControllerCommonHome extends Controller {

public function index() {

$this->cache->set('test','This is a test cache value');

var_dump($this->cache->get('test'));die;  

Let's see what happens:

OpenCart 3 6

Now, for the purity of the experiment, delete the line:

$this->cache->set('test','This is a test cache value');  

And see what happened. We pulled the data out of the cache.

Delete data from the cache.

To delete data from the cache, use:

$this->cache->delete('<key>')

Let's delete the data from the cache by the key "test", and then try to output data from the cache by the key "test":

<?php

class ControllerCommonHome extends Controller {

public function index() {

$this->cache->delete('test');

var_dump($this->cache->get('test'));die;

Let's see what happens:

OpenCart 3 7

Returned false, because there is no data in the cache with the "test" key.

Conclusion.

We have considered the basic principles of working with cache in OpenCart:

  • Retrieving data
  • Adding data
  • Deletion of data