Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom helper functions in OpenCart

Tags:

php

opencart

Trying to create a custom PHP function within opencart. Basically I need to know if we are viewing the cart or checkout pages. I understand the simplest way to accomplish this is by accessing the route request param. I want to create a re-usable function however that is available site wide.

Is this possible? Where would it go?

The function looks something like this:

function isCheckout() {

    $route = $this->request->get['route'];

    //is cart?
    if($route == 'checkout/cart')
        return 'cart';

    $parts = explode('/', $route);

    if($parts[0] == 'checkout')
        return 'checkout';

    return false;

}
like image 378
Chris Avatar asked Oct 24 '12 15:10

Chris


3 Answers

Put your helper file inside a helper folder inside a system directory

system/helper/myhelper.php

and include it to

system/startup.php file

like this

require_once(DIR_SYSTEM . 'helper/myhelper.php');

and you are done.

like image 196
Sanjay Avatar answered Nov 11 '22 02:11

Sanjay


Put the function in a file eg. myhelper.php and save this to ../system/library/

Then add

require_once(DIR_SYSTEM . 'library/myhelper.php');

to ../system/startup.php

like image 22
James Avatar answered Nov 11 '22 01:11

James


The correct and recommended way of doing this is using the OpenCart's built-in loader:

$this->load->helper('helper_name');

The helper is located in the directory system/helper. You don't need to append the php suffix when you load it, as OpenCart's loader engine appends it automatically.

And then, because the helper is not a class you use the functions directly without the $this. For example:

$this->load->helper('general');

token();

And the result will be a 32-character token. The token() function is located in the general helper in the system/helper directory.

This is an example of the general helper:

<?php
function token($length = 32) {
    // Create token to login with
    $string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

    $token = '';

    for ($i = 0; $i < $length; $i++) {
        $token .= $string[mt_rand(0, strlen($string) - 1)];
    }   

    return $token;
}
like image 3
user8581607 Avatar answered Nov 11 '22 01:11

user8581607