如何在opencart中创建全局函数


How to create global function in opencart

我正在尝试创建一个可以在任何页面上执行的简单函数

function something() {
    $string = 'Hello World'; 
    return $string;
}

假设我在类别页面中,我只需要调用$a = something();,它就会返回我的值

平台:OpenCart

p.S.我仍在学习MVC架构

由于您想要了解MVC系统,因此正确的方法是创建自己的帮助程序文件并将其放入/system/helper/,然后将帮助程序添加到system/startup.php。看看json.php/utf8.php是如何在这些中完成的,作为的指南

用相同的代码创建一个新文件到system/library/yourclassname.php。

此外,请将类名添加到您的函数中,如下所示:

class yourclassname {
  function something() {
    $string = 'Hello World'; 
    return $string;
  }
}

并将其添加到您的index.php文件中,如下所示;

$registry->set('yourclassname', new yourclassname($registry));

最后将其添加到startup.php文件中,如下所示:

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

你可以在任何地方使用$this->yourclassname->something();

仅此而已。。

您可以在任何opencart库(system/library/)中创建函数

例如system/library/document.php

    function something() {
    $string = 'Hello World'; 
    return $string;
}

并将开放艺术中的任何地方用作

$something=$this->document->something();

header.tpl中的p/s代码在ajax或直接请求中不起作用

Matricore的答案对我来说非常有效,但我也必须用可用的config和db构建新的类。

以下代码:

class yourclassname {
    public function __construct($registry) {
        $this->config = $registry->get('config');
        $this->db = $registry->get('db');
    }
}

然后,您可以通过$this->db->query("Your query here")运行查询;