问题
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;
}
回答1:
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.
回答2:
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
回答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;
}
来源:https://stackoverflow.com/questions/13052307/custom-helper-functions-in-opencart