【问题标题】:How to become an OpenCart guru? [closed]如何成为 OpenCart 大师? [关闭]
【发布时间】:2012-11-20 17:45:51
【问题描述】:

除了官方论坛上的一些 api 调用外,他们似乎没有任何文档。我有 Zend 框架和 CodeIgniter 框架的经验。任何 OpenCart 大师都可以推荐我在最短的时间内学习并掌握它的最佳方法吗?我必须尽快用它做一个大项目。

【问题讨论】:

标签: php opencart


【解决方案1】:

OpenCart 1.5.X 开发者初学者快速入门指南

本指南是为已经熟悉 PHP、OOP 和 MVC 架构的开发人员编写的

在下文中,您将看到购物车目录侧的示例。除了相关部分中提到的视图之外,管理端在功能上是相同的


了解库

所有库功能都可以通过控制器、模型和视图使用$this->library_name 访问。所有这些都可以在/system/library/ 文件夹中找到。例如,要访问当前购物车的产品,您需要使用Cart 类,该类位于/system/library/cart.php 中,可以使用$this->cart->getProducts() 访问

常用物品

  • customer.php - 客户相关功能
  • user.php - 管理用户相关功能
  • cart.php - 购物车相关功能
  • config.php - 所有设置都从这里加载
  • url.php - URL 生成函数

了解路由参数

OpenCart 的框架依赖于查询字符串参数中的route=aaa/bbb/ccc 来知道要加载什么,并且是查找需要为每个页面编辑的文件的基础功能。大多数路由实际上只使用aaa/bbb 这应该被视为两部分,但有些包含三个部分aaa/bbb/ccc 第一部分aaa 通常与通用文件夹中的文件夹相关,例如控制器或模板文件夹。第二部分通常与文件名有关,没有相关的.php.tpl 扩展名。第三部分在下面的“了解控制器”部分进行了解释


理解语言

语言存储在/catalog/language/ 文件夹的your-language 子文件夹中。其中,跨页面使用的一般文本值存储在文件夹内的your-language.php 文件中,因此对于目录端的英语,您将在catalog/language/english/english.php 中找到值。对于特定的页面文本,您需要页面的route(通常是这种情况,但不是总是,因为您可以指定任何您喜欢的语言文件)。例如,搜索页面有路由product/search,因此该页面的语言特定文本可以在catalog/language/english/product/search.php 中找到(注意文件名和子文件夹与.php 后面的路由匹配。

要在控制器中加载语言,请使用

$this->language->load('product/search');

然后就可以使用语言库函数get来检索特定的语言文本,比如

$some_variable = $this->language->get('heading_title');

语言变量在语言文件中使用特殊变量$_ 分配,该变量是键和文本值的数组。在您的/catalog/language/english/product/search.php 中,您应该找到类似于

$_['heading_title']     = 'Search';

全局语言文件english/english.php 中的值会自动加载,无需$this->language->load 方法即可使用


了解控制器

控制器是基于route 加载的,并且相当容易理解。控制器位于/catalog/controller/ 文件夹中。继续上一个示例,搜索页面的控制器位于此文件夹内的/product/search.php 中。再次注意.php后面的路由被使用了。

打开控制器文件,您会看到一个扩展 Controller 类的 Pascal Case 类名,称为 ControllerProductSearch。这又是特定于路由的,Controller 后跟子文件夹名称和文件名,扩展名不大写。大写实际上不是必需的,但为了便于阅读,建议使用它。值得注意的是,除了字母和数字之外,类名不会从子文件夹和文件名中获取任何值。下划线被删除。

类中有方法。声明为 public 的类中的方法可以通过路由访问以运行 - private 不是。默认情况下,使用标准的两部分路由(上面的aaa/bbb),调用默认的index() 方法。如果使用路由的第三部分(上面的ccc),则将运行此方法。比如account/return/insert会加载/catalog/controller/account/return.php文件和类,并尝试调用insert方法


了解模型

OpenCart 中的模型位于 /catalog/model/ 文件夹中,并根据功能而非路由进行分组,因此您需要通过

将它们加载到控制器中
$this->load->model('xxx/yyy');

这将加载名为yyy.php 的子文件夹xxx 中的文件。然后可以通过对象使用

$this->model_xxx_yyy

和控制器一样,你只能调用它的public 方法。例如,要调整图像大小,您可以使用tool/image 模型并调用其resize 方法,如下所示

$this->load->model('tool/image');
$this->model_tool_image->resize('image.png', 300, 200);

从控制器理解视图中的变量赋值

为了从控制器向视图传递值,您只需将数据分配给$this->data 变量,它本质上是一个键=> 值对的数组。举个例子

$this->data['example_var'] = 123;

如果您熟悉将每个键转换为变量的extract() 方法,那么在视图中访问它应该很容易理解。所以example_var 键变成$example_var 并且可以在视图中这样访问。


了解主题

主题仅在目录端可用,基本上是一个包含模板、样式表和主题图像的文件夹。主题文件夹放置在/catalog/view/theme/ 文件夹中,后跟主题名称。文件夹名称不重要,default 文件夹除外

管理端使用/admin/view/template/(跳过路径中的/theme/theme-name/,因为它不允许不同的主题)

模板文件位于主题文件夹内的template 文件夹中。如果当前选择的主题没有任何模板可用,则使用默认文件夹的模板作为备用。这意味着可以用很少的文件创建主题,并且仍然可以充分发挥作用。它还可以减少代码重复和升级时的问题


了解视图(模板)

与语言和模型一样,视图文件通常与路线相关,但根本不必如此。目录端的模板通常在/catalog/view/theme/your-theme/template/ 中找到,除非它不存在,在这种情况下将使用默认主题的模板。对于我们上面的搜索页面示例,文件是product/search.tpl。对于包含三个部分的路线,通常在aaa/bbb_ccc.tpl 中,尽管没有硬性规定。在管理员中,大多数页面都遵循此规则,除了列出项目的页面(如产品列表页面)在 catalog/product_list.tpl 中,产品编辑表单在 catalog/product_form.tpl 中。同样,这些不是设置的,而是默认购物车的标准。

模板文件实际上只是另一个 php 文件,但扩展名为 .tpl,并且实际上在控制器文件中运行,因此您可以在控制器中编写的所有内容都可以在模板文件中运行(虽然不是除非绝对必要,否则推荐)


了解数据库对象

查询使用

$result = $this->db->query("SELECT * FROM `" . DB_PREFIX . "table`");

DB_PREFIX 顾名思义是一个包含数据库前缀(如果存在)的常量

$result 将为SELECT 查询返回一个对象,其中包含一些属性

$result->row 包含第一行的数据,如果一个或多个作为关联数组返回

$result->rows 包含一个行结果数组,非常适合使用 foreach 进行循环

$result->num_rows 包含返回的结果数

$this->db 对象还有一些额外的方法

$this->db->escape() 在传递的值上使用mysql_real_escape_string()

$this->db->countAffected 返回受UPDATE 查询等影响的行数

$this->db->getLastId() 使用 mysql_insert_id() 返回最后一个自动增量 ID


了解保留变量

OpenCart 有预定义的变量来代替标准的$_GET$_POST$_SESSION$_COOKIE$_FILES$_REQUEST AND $_SERVER

$_SESSION 是使用 $this->session->data 编辑的,其中数据是一个模仿 $_SESSION 的关联数组

所有其他人都可以使用$this->request 访问,并且已经“清理”以符合启用/禁用的魔术引号,所以

$_GET 变为 $this->request->get

$_POST 变为 $this->request->post

$_COOKIE 变为 $this->request->cookie

$_FILES 变为 $this->request->files

$_REQUEST 变为 $this->request->request

$_SERVER 变为 $this->request->server


总结

虽然以上内容对于开发者来说并不是万无一失的指南,但希望它可以作为入门者的良好起点

【讨论】:

  • 谢谢!你从哪里弄到这个的?
  • 我写的。我认为它需要写作并适合这个问题
  • 非常好。比大多数指南提供更多信息。你有任何机会进阶吗?
  • 这应该被赋予社区 Wiki 状态
  • @UltimateKing - 本指南已经为您提供了足够多的信息来帮助您开始制作自己的模组。网上也有专门针对模块开发的教程
【解决方案2】:

全局库方法:基本的 opencart 库函数及其功能,其中大部分可以从目录或管理文件夹(控制器、模型、视图)中的任何位置调用

CACHE
$this->cache->delete($key) - Deletes cache [product, category, country, zone, language, currency,
manufacturer]

CART
$this->cart->getProducts() Gets all products currently in the cart including options, discounted prices, etc.
$this->cart->add( $product_id, $qty = 1, $options = array()) - Allows you to add a product to the cart
$this->cart->remove( $key ) - Allows you to remove a product from the cart
$this->cart->clear() - Allows you to remove all products from the cart
$this->cart->getWeight() - Sum of the weight of all products in the cart that have require shipping set to Yes
$this->cart->getSubTotal() - returns the subtotal of all products added together before tax
$this->cart->getTotal() - returns the total of all products added together after tax
$this->cart->countProducts() - returns the count of all product in the cart
$this->cart->hasProducts() - returns true if there is at least one item in the cart
$this->cart->hasStock() - returns false if there is at least one item in the cart that is out of stock
$this->cart->hasShipping() - returns true if there is at least one item in the cart that requires shipping
$this->cart->hasDownload() - returns true if there is at least one item in the cart that has a download
associated

CONFIG
$this->config->get($key) - returns setting value by keyname based on application (catalog or admin)
$this->config->set($key, $value) - set the value to override the setting value. DOES NOT SAVE TO DATABASE

CURRENCY
$this->currency->set($currency) - set or override the currency code to be used in the session
$this->currency->format($number, $currency = '', $value = '', $format = TRUE) - format the currency
$this->currency->convert($value, $from, $to) - convert a value from one currency to another. Currencies must
exist
$this->currency->getId() - get the database entry id for the current currency (1, 2, 3, 4)
$this->currency->getCode() - get the 3-letter iso code for the current currency (USD, EUR, GBP, AUD, etc)
$this->currency->getValue($currency) - get the current exchange rate from the database for the specified
currency.
$this->currency->has(currency) - Check if a currency exists in the opencart currency list

CUSTOMER
$this->customer->login($email, $password) - Log a customer in
$this->customer->logout() - Log a customer out
$this->customer->isLogged() - check if customer is logged in
$this->customer->getId() - get the database entry id for the current customer (integer)
$this->customer->getFirstName() - get customer first name
$this->customer->getLastName() - get customer last name
$this->customer->getEmail() - get customer email
$this->customer->getTelephone() - get customer telephone number
$this->customer->getFax() - get customer fax number
$this->customer->getNewsletter() - get customer newsletter status
$this->customer->getCustomerGroupId() - get customer group id
$this->customer->getAddressId() - get customer default address id (maps to the address database field)

DATABASE
$this->db->query($sql) - Execute the specified sql statement. Returns row data and rowcount.
$this->db->escape($value) - Escape/clean data before entering it into database
$this->db->countAffected($sql) - Returns count of affected rows from most recent query execution
$this->db->getLastId($sql) - Returns last auto-increment id from more recent query execution 4

DOCUMENT (*Called from controller only before renderer)
$this->document->setTitle($title) - Set page title
$this->document->getTitle()- Get page title
$this->document->setDescription($description) - Set meta description
$this->document->getDescription()- Get meta description
$this->document->setKeywords()- Set meta keywords
$this->document->getKeywords()- Get meta keywords
$this->document->setBase($base) - Set page base
$this->document->getBase() - Get page base
$this->document->setCharset($charset) - Set page charset
$this->document->getCharset() - Get page charset
$this->document->setLanguage($language) - Set page language
$this->document->getLanguage()- Get page language
$this->document->setDirection($direction) - Set page direction (rtl/ltr)
$this->document->getDirection()- Get page direction (rtl/ltr)
$this->document->addLink( $href, $rel ) – Add dynamic <link> tag
$this->document->getLinks()- Get page link tags
$this->document->addStyle( $href, $rel = 'stylesheet', $media = 'screen' ) – Add dynamic style
$this->document->getStyles()- Get page styles
$this->document->addScript( $script ) - Add dynamic script
$this->document->getScripts()- Get page scripts
$this->document->addBreadcrumb($text, $href, $separator = ' &gt; ') – Add breadcrumb
$this->document->getBreadcrumbs()- Get Breadcrumbs

ENCRYPT
$this->encryption->encrypt($value) - Encrypt data based on key in admin settings
$this->encryption->decrypt($value) - Decrypt data based on key in admin settings

IMAGE
$this->image->resize($width = 0, $height = 0)

JSON
$this->json->encode( $data )
$this->json->decode( $data , $assoc = FALSE)

LANGUAGE
$this->language->load($filename);

LENGTH
$this->length->convert($value, $from, $to) - convert a length to another. units must exist
$this->length->format($value, $unit, $decimal_point = '.', $thousand_point = ',') - format the length to use
unit

LOG
$this->log->write($message) - Writes to the system error log

REQUEST
$this->request->clean($data) - Cleans the data coming in to prevent XSS
$this->request->get['x'] - Same as $_GET['x']
$this->request->post['x'] - Same as $_POST['x']

RESPONSE
$this->response->addHeader($header) - additional php header tags can be defined here
$this->response->redirect($url) - redirects to the url specified

TAX
$this->tax->setZone($country_id, $zone_id) - Set the country and zone id for taxing (integer)
$this->tax->calculate($value, $tax_class_id, $calculate = TRUE) - Calculate all taxes to be added to the total
$this->tax->getRate($tax_class_id) - Get the rates of a tax class id
$this->tax->getDescription($tax_class_id) - Get the description of a tax class id
$this->tax->has($tax_class_id) - Check if a tax class id exists in opencart

SESSION
$this->session->data['x'] - Same as $_SESSION['x']  

【讨论】:

    【解决方案3】:

    有一个 OpenCart Wiki 网站,其中包含面向初学者开发人员的文档。 按照下面给出的网址了解更多详情:

    http://wiki.opencarthelp.com/doku.php?id=start
    http://wiki.opencarthelp.com/doku.php?id=methods_reference

    互联网存档链接

    http://web.archive.org/web/20160305131349/http://wiki.opencarthelp.com/doku.php?id=start http://web.archive.org/web/20160305131349/http://wiki.opencarthelp.com/doku.php?id=methods_reference

    例如方法参考包含以下详细信息:

    1. 客户登录
    2. 数据库访问
    3. 购物车处理
    4. 配置
    5. 缓存
    6. 货币处理

    还有一些页面正在建设中,但它会有所帮助。

    [更新]

    截至 2018 年 1 月,opencarhelp.com 域已关闭。

    【讨论】:

    • 几个月后似乎仍然缺少很多信息。这个项目被放弃了吗?
    • @Pacerier,我不确定。
    • 这是一个很棒的页面,即使打开购物车 wiki 也会引用它,您可以在此处查看链接 wiki.opencarthelp.com/doku.php?id=opencart_framework
    【解决方案4】:

    虽然这个话题已经回答了很多次,但我想根据我的经验提供另一种掌握 OpenCart 的方法。

    边做边学

    通过使用少量文件从头开始创建自己的 OpenCart 框架,您可以了解所有内容是如何组合在一起的。我将为您模拟 OpenCart 的文件结构。

    创建文件index.php

    <?php
    // My simpleCart
    
    

    1。注册表

    Opencart 使用注册表模式列出加载类的所有实例。它是您的 OpenCart 应用程序的核心。然后将注册表对象传递给每个类别、模型和库,以便快速访问其他对象。

    创建一个路径为/system/engine/registry.php的文件

    <?php
    // Registry class. 
    class Registry
    {
        private $data = array();
    
        public function set($key, $value){
            $this->data[$key] = $value;
        }
    
        public function get($key){
            return (isset($this->data[$key])) ? $this->data[$key] : false;
        }
    }
    
    

    在你的index.php

    <?php
    // My simpleCart
    
    //load dependency files
    require_once('system/engine/registry.php');
    
    //initialize registry
    $registry = new Registry;
    
    

    2。输出

    现在让我们添加一个输出,它将成为我们未来的 HTML。毕竟,整个想法是向浏览器发送一串文本。

    创建文件system/library/response.php

    <?php
    class Response {
        private $output;
    
        public function getOutput() {
            return $this->output;
        }
    
        public function setOutput($output) {
            $this->output = $output;
        }
    
        public function output() {
            if ($this->output) {
                echo $this->output;
            }
        }
    }
    

    在你的index.php

    <?php
    // My simpleCart
    
    //load dependency files
    require_once('system/engine/registry.php');
    require_once('system/library/response.php');
    
    //initialize registry
    $registry = new Registry;
    
    //initialize response
    $response = new Response;
    //add response object to the registry
    $registry->set('response', $response);
    
    //lets set an output as a test
    $registry->get('response')->setOutput('Hello World');
    
    //send the output to the client
    $registry->get('response')->output();
    
    

    请注意,我添加 Hello world 仅作为示例。我们将进一步删除它。刷新您的网站以检查它。浏览器应显示Hello World

    3。控制器

    将控制器视为页面。他们将定义将向客户端显示的内容:文本、html、json、下载甚至图像。目前,我们只需要一个发送文本的页面。

    我们将为home 页面创建一个控制器。

    添加路径为catalog/controller/common/home.php的文件

    <?php
    
    class ControllerCommonHome{
    
        private $registry = array();
    
        public function __construct($registry){
            $this->registry = $registry;
        }
    
        public function index(){
    
            $output = 'Home Page';
            //using the registry to get the response object and set the Output
            $this->registry->get('response')->setOutput($output);
        }
    }
    

    并编辑您的index.php

    <?php
    // My simpleCart
    
    //load registry
    require_once('system/engine/registry.php');
    //load response
    require_once('system/library/response.php');
    
    //initialize registry
    $registry = new Registry;
    
    //initialize response
    $response = new Response;
    //add resoinse object to the registry
    $registry->set('response', $response);
    
    //load controller common/home
    require_once('catalog/controller/common/home.php');
    $controller = new ControllerCommonHome($registry);
    $controller->index();
    
    //send the output to the client
    $registry->get('response')->output();
    

    注意我是如何将 $refistry 传递给 ControllerCommonHome 以便我可以在控制器内部访问它的。

    4。路由器

    我们不希望控制器被硬编码,对吧。我们将使用来自 url 地址的参数route 来告诉我们的购物车要加载哪个控制器。

    创建一个路径为system/library/request.php的文件

    <?php
    class Request {
        public $get = array();
    
        //for now I just need the $_GET parameter
        public function __construct() {
            $this->get = $_GET;
        }
    }
    

    创建Router类,该类将负责根据路由初始化Controller文件(换句话说:动态调用控制器)

    <?php
    class Router {
        private $registry;
    
        public function __construct($registry) {
            $this->registry = $registry;
        }
    
        public function dispatch($route) {
            require_once('catalog/controller/'.$route.'.php');
            $class = "Controller".str_replace('/', '', $route);
            $controller = new $class($this->registry);
            $controller->index();
        }
    }
    

    将其加载到您的index.php

    <?php
    require_once('system/engine/registry.php');
    require_once('system/engine/router.php');
    require_once('system/library/response.php');
    require_once('system/library/request.php');
    
    $registry = new Registry;
    
    $response = new Response;
    $registry->set('response', $response);
    
    $request = new Request;
    $registry->set('request', $request);
    
    //get the route from the url
    if(isset($registry->get('request')->get['route'])){
        $route = $registry->get('request')->get['route'];
    }else{
        $route = 'common/home';
    }
    
    //initiate the router and dispatch it base on the route
    $router = new Router($registry);
    $router->dispatch($route);
    
    
    $registry->get('response')->output();
    

    注意我如何将所有内容加载到$registry,然后将其传递给$router,然后再将其传递给$controller

    这篇文章已经太长了,但我希望它能对 OpenCart 中的 MVC 模式有一个基本的了解。

    如果您希望我继续这篇文章并告诉您其他事物(例如模型和视图)的工作原理,请评价此答案,以便我知道。

    还可以查看我的 Youtube https://www.youtube.com/dreamvention 和我的博客 https://dreamvention.com/blog 我将在那里为你们发布更多提示和教程!

    【讨论】:

      【解决方案5】:

      PHP 是一门相当大的语言,over 5000 built-in functions 因此学习新平台的一个策略是确定它最常使用的功能,并花一些时间来很好地了解这些功能。

      我对 OpenCart 源代码进行了一些查询,最常用的前 10 个函数是:

      array()
      count()
      explode()
      implode()
      mktime()
      delete()
      time()
      date()
      sprintf()
      list()
      

      此处列出的所有 52 个命令以及您可以在任何代码库上使用的 Linux bash 命令来识别常用函数: https://www.antropy.co.uk/blog/efficient-learning-for-new-opencart-developers/

      【讨论】:

        【解决方案6】:

        这个 youtube 视频播放列表也有助于成为 OpenCart 开发者大师:

        OpenCart Videos Tutorials

        1. Introduction and Table of Contents这个视频是系列的介绍
        2. OpenCart installation localhost本视频在localhost中安装OpenCart
        3. Files and folder structure of Opencart 描述OpenCart的文件和文件夹结构
        4. Creating Database Table schema in OpenCart 它显示了数据库表模式并显示了如何在 OpenCart 中创建数据库表
        5. OpenCart Library Predefined Objects’ Methods 它描述了 OpenCart 库预定义对象的方法并显示了在哪里可以找到它们。
        6. MVCL pattern, code flow and request & response in OpenCart 它显示了 OpenCart 中的 MVCL 模式、代码流以及请求和响应。 他们描述了如下图所示的流程:

        7. Install, Configure and Uninstall Opencart module 它显示了三种上传模块的方法,然后安装、配置和卸载 OpenCart 3 模块/扩展。

        8. Layouts and position in Opencart 3 它描述了 OpenCart 3 的布局和位置。它展示了如何显示不同页面的自定义布局,并给出了类别页面的示例。我们为不同的类别展示了不同的布局。

        9. Event overview of Opencart您将了解 OpenCart 中的事件、它们的工作原理以及它们为何如此有用。

        10. Opencart API documentation for developer这个视频将展示如何使用和制作自定义opencart API

        看到这些视频后,您就可以开始编码了 :)

        【讨论】:

          猜你喜欢
          • 2012-03-03
          • 1970-01-01
          • 2015-07-14
          • 2010-12-24
          • 2017-03-30
          • 1970-01-01
          • 2017-06-17
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多