php 如何成为 OpenCart 大师?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13478995/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 05:32:31  来源:igfitidea点击:

How to become an OpenCart guru?

phpopencart

提问by CodeCrack

It seems like they have no documentation except some api calls on their official forums. I have experience with Zend framework and CodeIgniter framework. Can any OpenCart masters recommend me the best way to learn it and master in shortest amount of time? I have to do a big project with it soon.

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

回答by Jay Gilford

OpenCart 1.5.X developer quick start guide for beginners

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

This guide is written for developers already familiar with PHP, OOP and the MVC architecture

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

In the following, you'll see examples for the catalog side of the cart. The admin side is identical in function with the exception of the views which is noted in the relevant section

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



Understanding Libraries

了解图书馆

All of the library functionality is accessible through Controller, Model and Views using $this->library_name. All of these can be found in the /system/library/folder. For example, to access the current shopping cart's products, you'll need to use the Cartclass, which is in /system/library/cart.phpand can be accessed using $this->cart->getProducts()

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

Commonly used items

常用物品

  • customer.php- Customer related functions
  • user.php- Admin user related functions
  • cart.php- Cart related functions
  • config.php- All settings are loaded from this
  • url.php- URL generation functions
  • customer.php- 客户相关功能
  • user.php- 管理员用户相关功能
  • cart.php- 购物车相关功能
  • config.php- 所有设置都从这里加载
  • url.php- 网址生成功能


Understanding the route parameter

了解路由参数

OpenCart's framework relies on the route=aaa/bbb/cccin the query string parameter to know what to load, and is the underpinning feature to finding the files you need to edit for each page. Most route's actually only use the aaa/bbbwhich should be seen as two parts, however some contain three parts aaa/bbb/cccThe first part aaagenerally related to the folder within a generic folder such as the controller or template folders. The second part usually relates to the file name, without the relevant .phpor .tplextension. The third part is explained in the section "Understanding controllers" below

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



Understanding languages

理解语言

Languages are stored in /catalog/language/folder in the your-languagesubfolder. Within this, general text values used across various pages are stored in the your-language.phpfile inside the folder, so for the English language on the catalog side, you'll find the values in catalog/language/english/english.php. For specific page text, you'll need the routefor the page (This is generally the case, but not alwaysas you can specify any language file you like). For example, the search page has the route product/search, and therefore the language specific text for that page can be found in catalog/language/english/product/search.php(Notice the file's name and subfolder match the route followed by .php.

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

To load the language in a controller, you use

要在控制器中加载语言,您可以使用

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

Then you can use the language library function getto retrieve specific language texts, such as

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

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

The language variables are assigned in the language file using a special variable $_which is an array of keys and text values. In your /catalog/language/english/product/search.phpyou should find something similar to

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

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

The values in the global language file english/english.phpare automatically loaded and available to use without the $this->language->loadmethod

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



Understanding controllers

了解控制器

Controllers are loaded based on the routeand are fairly straight forward to understand. Controllers are located in the /catalog/controller/folder. Continuing from the last example, the Controller for the Search page is in /product/search.phpwithin this folder. Notice again that the route followed by .phpis used.

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

Opening the controller file, you'll see a Pascal Case classname extending the Controllerclass, called ControllerProductSearch. This again is specific to the route, with Controllerfollowed by the subfolder name and file name without the extension capitalised. The capitalisation is not actually required, but it's recommended for easy readability. It's worth noting that classnames don't take any values from the subfolder and file name other than letters and numbers. Underscores are removed.

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

Within the class are the methods. Methods in the class declared publicare accessible to be run via the route - privateare not. By default, with a standard two part route (aaa/bbbabove), a default index()method is called. If the third part of a route (cccabove) is used, this method will be run instead. For example, account/return/insertwill load the /catalog/controller/account/return.phpfile and class, and try to call the insertmethod

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



Understanding Models

理解模型

Models in OpenCart are found in the /catalog/model/folder and are grouped based on function, not route, and therefore you will need to load them in your controller via

OpenCart 中的模型位于/catalog/model/文件夹中,并根据功能而不是路线进行分组,因此您需要通过以下方式将它们加载到控制器中

$this->load->model('xxx/yyy');

This will load the file in the subfolder xxxcalled yyy.php. It is then available to use via the object

这将加载xxx名为yyy.php. 然后可以通过对象使用

$this->model_xxx_yyy

and as with controllers, you can only call its publicmethods. For instance, to resize an image, you would use the tool/imagemodel and call its resizemethod as follows

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

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


Understanding variable assignment in views from the controller

从控制器了解视图中的变量分配

In order to pass values to the view from the controller, you simply need to assign your data to the $this->datavariable, which is essentially an array of key => value pairs. As an example

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

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

Accessing this in a view is a little should be easy to understand if you're familiar with the extract()method which converts each key into a variable. So the example_varkey becomes $example_varand can be accessed as such in the view.

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



Understanding themes

理解主题

Themes are available to the catalog side only, and are basically a folder of templates, stylesheets and theme images. Theme folders are placed in the /catalog/view/theme/folder followed by the theme name. The folder name isn't of importance with exception to the defaultfolder

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

The admin side uses /admin/view/template/(skipping the /theme/theme-name/from the path as it doesn't allow differing themes)

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

Template files reside in a templatefolder within the theme folder. Should any template not be available for the currently selected theme, the default folder's template is used instead as a fallback. This means themes can be created with very few files and still function fully. It also reduces code duplication and issues as upgrades are made

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



Understanding views (templates)

理解视图(模板)

As with language and models, the view file's are generally related to the route, though don't have to be at all. Templates on the catalog side are usually found in /catalog/view/theme/your-theme/template/unless it doesn't exist, in which case the default theme's templates will be used. For our search page example above, the file is product/search.tpl. For routes with three parts, it is generally in aaa/bbb_ccc.tplthough there's no hard set rule. In the admin, most pages follow this, with the exception that pages listing items, like the product listing page, are in catalog/product_list.tpland the product editing form is in catalog/product_form.tpl. Again, these aren't set, but a standard for the default cart.

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

The template file is in fact just another php file, but with a .tpl extension and is actually run in the controller file, therefore all of the things you can code in a controller can be run in a template file (though not recommended unless absolutely necessary)

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



Understanding the database object

了解数据库对象

Queries are run using

查询运行使用

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

DB_PREFIXas the name suggests is a constant containing the database prefix if one exists

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

$resultwill return an object for SELECTqueries, containing a few properties

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

$result->rowcontains the first row's data if one or more are returned as an associative array

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

$result->rowscontains an array of row results, ideal for looping over using foreach

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

$result->num_rowscontains the number of results returned

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

There are also a few extra methods the $this->dbobject has

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

$this->db->escape()uses mysql_real_escape_string()on the value passed

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

$this->db->countAffectedreturns the number of rows affected by an UPDATEquery and so on

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

$this->db->getLastId()returns the last auto increment id using mysql_insert_id()

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



Understanding reserved variables

了解保留变量

OpenCart has predefined variables to use in place of the standard $_GET, $_POST, $_SESSION, $_COOKIE, $_FILES, $_REQUESTAND $_SERVER

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

$_SESSIONis edited using $this->session->datawhere data is an associative array mimicking the $_SESSION

$_SESSION使用$this->session->datawhere data 是一个模拟数组的关联数组进行编辑$_SESSION

All of the others can be accessed using $this->requestand have been "cleaned" to comply with magic quotes enabled/disabled, so

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

$_GETbecomes $this->request->get

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

$_POSTbecomes $this->request->post

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

$_COOKIEbecomes $this->request->cookie

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

$_FILESbecomes $this->request->files

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

$_REQUESTbecomes $this->request->request

$_REQUEST变成 $this->request->request

$_SERVERbecomes $this->request->server

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



Summary

概括

While the above isn't a bulletproof guide for developers, hopefully it will serve as a good starting point for those getting started

虽然以上内容不是开发人员的防弹指南,但希望它可以作为入门者的良好起点

回答by Abdul Rehman

Global Library Methods : Basic opencart library functions along with their functionalities, Most of these can be called from anywhere in the catalog or admin folders (controllers, models, views)

全局库方法:基本的 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']  

回答by Dharmang

There is a OpenCart Wiki website with documentation for beginner developers. Follow the urls given below for more details:

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

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

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

INTERNET ARCHIVE links

互联网档案链接

http://web.archive.org/web/20160305131349/http://wiki.opencarthelp.com/doku.php?id=starthttp://web.archive.org/web/20160305131349/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

E.g. Method reference has details for :

例如方法参考具有以下详细信息:

  1. Customer Login
  2. DB Access
  3. Shopping Cart Handling
  4. Config
  5. Cache
  6. Currency Handling
  1. 客户登录
  2. 数据库访问
  3. 购物车处理
  4. 配置
  5. 缓存
  6. 货币处理

Still There are some pages under construction but it is going to be helpful.

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

[Update]

[更新]

As of Jan-2018, opencarhelp.com domain is down.

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

回答by Dmitriy Zhuk

Although this topic has been answered many times already, I would like to offer another approach to mastering OpenCart based on my experience.

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

Learning by doing

边干边学

By creating your own OpenCart framework from scratch with a handful of files you can understand how everything is put together. I will be mimicking the file structure of OpenCart for you.

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

Create a file index.php

创建文件 index.php

<?php
// My simpleCart

1. Registry

1. 注册表

Opencart uses the Registry pattern to list all instances of loaded classes. It is the heart of your OpenCart app. The registry object is then passed around to every category, model, and library for quick access to other objects.

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

create a file with path /system/engine/registry.php

创建一个带路径的文件 /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;
    }
}

in your index.php

在你的 index.php

<?php
// My simpleCart

//load dependency files
require_once('system/engine/registry.php');

//initialize registry
$registry = new Registry;

2. Output

2. 输出

Now let's add an output which will be our HTML in the future. After all, the whole idea is to send a string of text to the browser.

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

Create file system/library/response.php

创建文件 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;
        }
    }
}

and in your index.php

并且在你的 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();

Notice I added Hello world only as an example. We will remove it further on. Refresh your site to check it. The browser should display Hello World.

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

3. Controllers

3. 控制器

Think of Controllers as pages. They will define what will be displayed to the client: text, html, json, download or even an image. For now, we just want a page that sends text.

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

We will create a controller for the homepage.

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

add a file with path catalog/controller/common/home.php

添加带路径的文件 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);
    }
}

and edit your index.php

并编辑您的 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();

notice how I passed the $refistryto the ControllerCommonHome so that I could access it inside the controller.

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

4. Router

4. 路由器

We don't want controllers to be hardcoded, right. We will use a parameter routefrom the url address to tell our cart which controller to load.

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

Create a file with path system/library/request.php

用路径创建文件 system/library/request.php

<?php
class Request {
    public $get = array();

    //for now I just need the $_GET parameter
    public function __construct() {
        $this->get = $_GET;
    }
}

Create the Router class that will be responsible for initializing the Controller file based on the route (in other words: dynamically call the controller)

创建 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();
    }
}

load it into your index.php

加载到你的 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();

Notice how I load everything into the $registryand then pass it to the $routerwhich then passes it to the $controller.

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

This post is already too long, but I hope it will give a basic understanding of the MVC pattern in OpenCart.

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

If you want me to continue with this post and tell you how other things work like models and views, rate this answer so that I know.

如果你想让我继续这篇文章并告诉你其他东西是如何工作的,比如模型和视图,请评价这个答案,以便我知道。

Also check out my Youtube https://www.youtube.com/dreamventionand my blog https://dreamvention.com/blogI will be posting more tips and tutorials there for you guys!

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

回答by Paul Feakins

PHP is a fairly large language with over 5000 built-in functionsso one strategy for learning a new platform is to identify which functions it uses most frequently and spend some time getting to know those very well.

PHP 是一种相当大的语言,拥有 5000 多个内置函数,因此学习新平台的一个策略是确定它最常使用哪些函数,并花一些时间来深入了解这些函数。

I've run some queries on the OpenCart source code and the top 10 most commonly used functions are:

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

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

All 52 listed here as well as Linux bash commands you can use on any codebase to identify commonly used functions: https://www.antropy.co.uk/blog/efficient-learning-for-new-opencart-developers/

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

回答by Rupak Nepali

This youtube videos playlist can also be helpful to become OpenCart developer Gurus:

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

OpenCart Videos Tutorials

OpenCart 视频教程

  1. Introduction and Table of ContentsThis video goes through the introduction of the series
  2. OpenCart installation localhostThis video go through the OpenCart installation in localhost
  3. Files and folder structure of OpencartIt describes files and folders structure of OpenCart
  4. Creating Database Table schema in OpenCartIt shows database table schema and shows how to create database tables in OpenCart
  5. OpenCart Library Predefined Objects' MethodsIt describes OpenCart Library Predefined Objects' Methods and shows where to find them.
  6. MVCL pattern, code flow and request & response in OpenCartIt shows MVCL pattern, code flow and request & response in OpenCart. They describe the flow as in the picture below: MVCL described with Code

  7. Install, Configure and Uninstall Opencart moduleIt shows three ways to upload modules, then install, configure and uninstall the OpenCart 3 module/extension.

  8. Layouts and position in Opencart 3It describes the OpenCart 3 layouts and positions. It shows how to show customize layouts for different pages, giving examples of categories pages. We show the different layout for a different category.

  9. Event overview of OpencartYou will learn what Events are in OpenCart, how they work and what makes them so useful.

  10. Opencart API documentation for developerThis video will show how to use and make custom opencart API

  1. 介绍和目录本视频介绍了该系列
  2. OpenCart 安装 localhost该视频介绍了在 localhost 中的 OpenCart 安装
  3. Opencart 的文件和文件夹结构 描述了 OpenCart 的文件和文件夹结构
  4. 在 OpenCart 中创建数据库表模式它显示了数据库表模式并展示了如何在 OpenCart 中创建数据库表
  5. OpenCart 库预定义对象的方法它描述了 OpenCart 库预定义对象的方法并显示了在哪里可以找到它们。
  6. OpenCart 中的MVCL 模式、代码流和请求与响应它展示了OpenCart 中的MVCL 模式、代码流和请求与响应。他们描述的流程如下图所示: 用代码描述的MVCL

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

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

  9. Opencart 事件概述您将了解 OpenCart 中的事件、它们如何工作以及是什么使它们如此有用。

  10. 开发人员的 Opencart API 文档该视频将展示如何使用和制作自定义 opencart API

Once you see these videos then you can start coding :)

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