OpenCart在自定义php脚本中添加产品

I want to add products via my script which is not connected with OpenCart.

For example: somedir/index.php. I try to do it in this way:

$productData = array(
    'model' => 'ABC123',

    'name'=>'aaa',
    'description'=>'aaa',
    'tag'=>'aaa',
    ...
);

require_once ('../../system/engine/model.php');
require_once ('../../admin/model/catalog/product.php');

$a= new ModelCatalogProduct();
$a->addProduct($productData);

But there are many functions that need to be triggered. How can this be achieved?

OpenCart uses a so called MVC-pattern. This patteren works within OpenCart in a very specialised and deeply coupled way, so you need the context of the routing system in case you would like to use controllers and models in your code.

Also, it really depends on which version you use, what semantics would be right, so that is hard to tell. Conceptually, you would do something like this: - define a new contoller in the /admin/controller directory structure, i.e. /admin/controller/tool/product_import.php

  • Call that controller ControllerToolProductImport which extends Controller;
  • Create a public function index()
  • Have it load the model like $this->load->model("catalog/product");
  • Now the model function becomes available and you would use it like $this->model_catalog_product->addProduct($productData);
  • This public function index can be triggerd by https://hostname:port/admin/index.php?route=too/product_import&token=ABC (you'll see what the token should be, once logged in into the admin section). To trigger another function within that controller directly (it needs to be public), you could extend the route easily. So for public function doSomething() it would become https://hostname:port/admin/index.php?route=too/product_import/doSomething&token=ABC.
  • When triggering this function from within the admin section, you would use the OpenCart functions to do so. Depending on your version, this would go like this for 2.2.0.0:

    $this->url->link('tool/product_import', 'token=' . $this->session->data['token'], true)