Although OpenCart provides lots of features in the core itself, you'll often find yourself in the situation in which you'll want to integrate a third-party library with it. OpenCart has a concept of the library which provides a common set of APIs for day-to-day operations like interacting with the configuration system or database system, dealing with an email system, etc. Today, we'll see how you could implement your own custom library in OpenCart.
In this article, we're going to create a custom library which will allow you to make CURL calls. We'll try to keep things simple and straightforward, as the important thing to understand is the concept itself—the implementation may vary based on the complexity.
We'll use the latest version of OpenCart. I also assume that you're aware with the module structure of OpenCart.
What Is a Library in OpenCart?
So, what exactly is a library in OpenCart? In simple terms, it's a set of utility scripts providing us the functionality used commonly in the framework. In OpenCart, you'll find all the libraries under the system/library
directory. For example, an incoming request is handled by the Request library, and for response handling there's the Response library. Similarly, there are libraries for caching, customer, database, and the configuration system, just to name a few.
Generally, you'll load the required libraries in your controller/model code as needed. You need to do something like this to load any library:
$cache = $this->load->library('cache');
In the above example, we've loaded the cache library. So from now on, you'll be able to use the $cache
object to call the methods defined in that library. As you can see, it's really a flexible way to load the objects as needed.
Today, we'll implement a curl library so that you can use it to make CURL calls using that library. It'll be helpful to avoid the code duplication in the controllers, as for every CURL request you'll need to instantiate the object and set up the common headers. We'll wrap it up in the common library so that it's reusable and avoids code duplication across the modules.
Before we go ahead and start our custom library implementation, let's have a quick look at one of the core libraries of OpenCart.
Explore the Core Library Code
As, we've already discussed the cache library in the previous section, let's explore the code of that library. Go ahead and open system/library/cache.php
in your favorite text editor.
<?php class Cache { private $cache; public function __construct($driver, $expire = 3600) { $class = 'Cache\\' . $driver; if (class_exists($class)) { $this->cache = new $class($expire); } else { exit('Error: Could not load cache driver ' . $driver . ' cache!'); } } public function get($key) { return $this->cache->get($key); } public function set($key, $value) { return $this->cache->set($key, $value); } public function delete($key) { return $this->cache->delete($key); } }
Pretty easy stuff, isn't it? It provides a simple class-based implementation with the required methods. Although it's a very simple example, it could be fairly complex for your use case! Go ahead and explore a couple more libraries to get yourself familiar with the concept.
Create a Custom Library: Curl
So now, you're aware with the core libraries, let's create our own! Create a system/library/curl.php
with the following contents.
<?php class Curl { private $logger; private static $instance; /** * @param object $registry Registry Object */ public static function get_instance($registry) { if (is_null(static::$instance)) { static::$instance = new static($registry); } return static::$instance; } /** * @param object $registry Registry Object * * You could load some useful libraries, few examples: * * $registry->get('db'); * $registry->get('cache'); * $registry->get('session'); * $registry->get('config'); * and more... */ protected function __construct($registry) { // load the "Log" library from the "Registry" $this->logger = $registry->get('log'); } /** * @param string $url Url * @param array $params Key-value pair */ public function do_request($url, $params=array()) { // log the request $this->logger->write("Initiated CURL request for: {$url}"); // init curl object $ch = curl_init(); curl_setopt($ch,CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // prepare post array if available $params_string = ''; if (is_array($params) && count($params)) { foreach($params as $key=>$value) { $params_string .= $key.'='.$value.'&'; } rtrim($params_string, '&'); curl_setopt($ch,CURLOPT_POST, count($params)); curl_setopt($ch,CURLOPT_POSTFIELDS, $params_string); } // execute request $result = curl_exec($ch); // close connection curl_close($ch); return $result; } }
We've defined a Curl
class with a handful of methods.
Starting with the get_instance
method, it allows us to create an object of the class itself. It'll also make sure that at any given time we'll have a single instance of the class.
Next, we've defined the constructor with the $registry
argument. Of course, you don't need any argument, but for example purposes I've used it to demonstrate how to load other libraries using the $registry
object. In our example, we're loading the Log
library and assigning it to the logger
property. We'll use this library to log the curl requests for debugging purposes!
Finally, there's a do_request
method which does all the heavy lifting for us! There are two arguments: $url
holds the URL to which we'll make the curl request, and $params
holds an optional array of parameters in case we need to POST any data. The code following that is fairly straightforward to understand: it makes a curl call and returns the response!
So we've almost finished with our custom library set up. We'll see it in action in the next section.
How to Use Our Custom Library
Most of the time, you'll end up calling libraries from the controller itself. So, let's see how to load and use our library from the controller.
// load curl library $this->load->library('curl'); $obj_curl = Curl::get_instance($this->registry); $result = $obj_curl->do_request($url); $result = $obj_curl->do_request($url, $params); // in case of $params needed
The $this->load->library('curl')
statement will load our custom library. In the next statement, we've called the get_instance
method and passed the $registry
object as a constructor argument. Finally, we've used the do_request
method to make the curl calls!
So, as you can see, it's quite easy to create your own libraries in OpenCart! Similarly, you could integrate any third party library in OpenCart library format and use it throughout the framework as needed.
Conclusion
Today, we've discussed the concept of a library in OpenCart.
If you're looking for additional libraries to use or to explore, don't forget to see what we have available in our marketplace.
We've explored the core libraries and created our own library for curl. I hope you've enjoyed it! Share your thoughts and queries using the feed below!
Comments