Custom helper functions in OpenCart
Asked Answered
S

3

5

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;

}
Saleem answered 24/10, 2012 at 15:22 Comment(2)
what is the problem .... first try thisBakst
Where do I put that? I don't know much about OpenCart. I have found that adding it to catalog/controller/common/header.php as a new function works fine, but will this be overwritten in an upgrade?Saleem
E
17

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.

Epicontinental answered 24/6, 2013 at 10:53 Comment(0)
T
4

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

Theomancy answered 24/10, 2012 at 18:58 Comment(2)
And this will not be effected in an update? This would be considered the documented method? Thanks for the help.Saleem
why not put the helper files in helper folder rather than library folderEpicontinental
H
3

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;
}
Hulbard answered 29/8, 2018 at 12:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.