No matter the web framework you’re working with, caching is an important tool to have in the kitty to improve the overall performance of your website. You have different caching mechanisms to choose from, like file, APC, Memcached and more. You can decide based on your requirements, and sometimes it takes a combination of more than one adapter to justify the desired outcome.
OpenCart already includes a couple of caching adapters in the core, and that’s what provides a template to follow should you want to create a custom one. To implement a custom adapter, you just need to create methods as per the contract and include your logic in each method, and you’re done! It’ll be picked up automatically as a part of the OpenCart caching mechanism.
For each caching adapter, it’s only the underlying mechanism to store and retrieve data that changes. The same is true for our custom database caching adapter too, and that’s why we need to create a custom schema that holds the caching data.
Make sure that you’ve installed the latest version of OpenCart before we go ahead and start creating a custom adapter.
Create an Adapter Schema
It’s a dbcache
MySQL table that’s going to hold our caching data. So, let’s create it!
CREATE TABLE IF NOT EXISTS `{DB_PREFIX}dbcache` ( `key` varchar(255) NOT NULL, `value` longblob NOT NULL, `expire` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
The important thing to note here is the database prefix; if you’re using it, make sure that you name your table accordingly. For example, in the case of database prefix oc_
, you should create a table named oc_dbcache
.
Other than that, the structure of table is quite simple, and it holds only three columns—key, value, and expire. The key column holds the caching key, the value column holds the associated value, and the expire column holds the UNIX time-stamp.
Create an Adapter File
You’ll find all the caching adapters provided by OpenCart under the system\library\cache
directory. Our custom adapter must go there too, so let’s create a file system\library\cache\database.php
with the following contents.
<?php namespace Cache; class Database { private static $_db; private $expire; /** * Constructor * * @param timestamp $expire Caching time in seconds */ public function __construct($expire) { $this->expire = $expire; $this->initDbInstance(); } /** * Helper method to create DB instance */ private function initDbInstance() { if (is_null(static::$_db)) { static::$_db = new \DB(DB_DRIVER, DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE, DB_PORT); } } /** * Fetch the value stored in cache by key * * @param string $key Cache Key * * @return mixed Value of cache key if found, boolean false otherwise */ public function get($key) { $query = static::$_db->query("SELECT * FROM `" . DB_PREFIX . "dbcache` WHERE `key` = '" . $key . "' AND `expire` >= '" . time() ."'"); if ($query->num_rows) { return unserialize($query->row['value']); } return false; } /** * Set the cache value by key * * @param string $key Cache Key * @param mixed $value Cache value */ public function set($key, $value) { $this->delete($key); static::$_db->query("INSERT INTO " . DB_PREFIX . "dbcache SET `key` = '" . $key . "', `value` = '" . mysql_escape_string(serialize($value)) . "', `expire` = '" . (time() + $this->expire) . "'"); } /** * Delete the value stored in cache by key * * @param string $key Cache Key */ public function delete($key) { static::$_db->query("DELETE FROM " . DB_PREFIX . "dbcache WHERE `key` = '".$key."'"); } }
As per the conventions, the class Database
is defined under the Cache
namespace. There are two properties, $_db
and $expire
. $_db
holds the database instance, and $expire
is set to cache lifetime when the class is instantiated. The reason behind declaring the $_db
property as static is the singleton object it holds.
In the constructor of class, we’re assigning the caching time passed from the OpenCart framework to the $expire
property and calling the initDbInstance
method defined in the same class that creates and assigns a database instance to $_db
if it doesn't already exist.
Next, the get
method is used to fetch a cache entry by key and expire time, and the set
method is used to insert a new cache entry in the database. Also, we’re serializing the cache data in the set
method to make sure that it’s stored properly. Of course, we need to unserialize it in the get
method before we actually return it!
Finally, there’s a delete
method that deletes an entry from database. It’s interesting to note here that the set method calls the delete method every time to make sure that we don’t end up creating duplicate cache entries!
So, that’s it as far as our custom caching adapter file setup is concerned. In the next section, we’ll see how to plug it in to the OpenCart core framework.
Plug in Our Custom Caching Adapter
Unfortunately, there’s no back-end configuration that allows you to plug in your custom caching adapter. So, for the sake of this tutorial, we’ll go ahead and directly influence the way it’s handled in the core.
Go ahead and open index.php
under the document root of your site.
Find the following snippet.
$cache = new Cache('file');
Replace it with:
$cache = new Cache(database');
So, as you can see, we’ve just changed the argument, or rather the adapter name, that’s passed when creating a new $cache
object.
In the same way, do it for the index.php
file that resides under the admin
directory. It makes sure that both the front-end and back-end use our custom caching adapter.
You’re almost done! Go ahead and visit a couple of pages in the front-end and back-end, and you should see that the dbcache
MySQL table is being filled up with new records!
In this way, you could go ahead and create a caching adapter for other storage engines as well. Although we’ve demonstrated it in a simple way, I think it’s the concept that matters the most for your next custom adapter!
Conclusion
As always, if you're looking for additional OpenCart tools, utilities, extensions, and so on that you can leverage in your own projects or for your own education, don't forget to see what we have available in the marketplace.
Today, we’ve discussed how to create a custom caching adapter in OpenCart. The database caching adapter was created in the process for demonstration. Feel free to post your queries using the feed below!
Comments