5

I am using Opencart Version 2.1.0.1, how to load frontend model in admin controller,

i have a model function which tells external booking id

class ModelShippingParcelled extends Model {
        public function getParcelledBooking($order_id) {
             $query = $this->db->query("SELECT booking_id FROM " . DB_PREFIX . "parcelled WHERE order_id = '" . (int)$order_id . "'");
             return $query->row;
    }

I want to load this model in admin controller. What is the best way to do this? Should I rewrite this model in admin too? But I don't want to rewrite the same function. If there is a good way please suggest!

Zsolti
  • 1,571
  • 1
  • 11
  • 22
rb16
  • 346
  • 3
  • 8
  • More often than not you'll end up needing some extra model functionality in the admin area, so just create an admin model with the duplicated code for now. That way it also follows the intended architecture (admin and catalog should be able to operate independent of each other) – Mavelo May 08 '16 at 14:16
  • @Mavelo *the intended architecture* – this is not "architecture", this is a joke. The only reason to *just create (…) duplicated code for now* is if one plans to migrate away from Opencart anyway, and one actually should. – ᴍᴇʜᴏᴠ Dec 31 '21 at 06:04

3 Answers3

2

Well, there is one ugly trick to achieve what you want. Example if you want to use the frontend's catalog/product model from your admin controller, then you can:

require_once DIR_CATALOG . "model/catalog/product.php";
$product = new ModelCatalogProduct($this->registry);

This will work also when you want to use the admin model from the frontend controller, just change the require statement.

ᴍᴇʜᴏᴠ
  • 4,804
  • 4
  • 44
  • 57
Zsolti
  • 1,571
  • 1
  • 11
  • 22
  • 2
    With this approach you might end with redeclarion fatal error, because all most in admin and catalog are named identically. But I agree, that its's the only solution besides copying or reproducing model functions directly. – The Krotek Nov 11 '16 at 00:00
1

I also needed to call a function from catalog/model inside admin/model (without copying). Requiring a function occured to be imposible in php. But I figured out that I can move the function into system/library, for example in /system/library/cart/cart.php. Albeit cart functions is never called in admin it occured to be possible. So I called it like

$this->cart->functionName($params)

To make sure function is still working in catalog I made replacement via shell like

find catalog -type f -print0 | xargs -0 sed -i '' -e 's/this->model_catalog_filter->functionName/this->cart->functionName/g'

Hebe
  • 661
  • 1
  • 7
  • 13
0

I suggest that you make a copy of the model in the admin folder. And if you are sure which functions you are gonna use copy only them.

Angel Miladinov
  • 1,596
  • 4
  • 20
  • 43