How does OpenCart access its library classes?

opencart, php

Solution

Firstly, your `ControllerCheckoutCart` extends the `Controller` class, so this is the class we need to focus on. You can find this class in `/system/engine/controller.php`.

Inside this class, there are two magic methods we are interested in. The first is the `__construct`, where the "registry" class is loaded (found in `/system/engine/registry.php` if you're interested in picking that apart - it's very simplistic).

You can think of this as a lookup of all the classes the store uses, such as model files, library files and so on. In the construct, the registry is passed to the controller so it has a reference to it

public function __construct($registry) {
    $this->registry = $registry;
}

The second and more important magic method is the `__get` method. This is called when a classes property doesn't exist, for you to handle it yourself if you wish to do so. OpenCart uses this to try and get the class with that key from the registry

public function __get($key) {
    return $this->registry->get($key);
}

So `$this->cart` in any controller would try to get the object with the key `cart` from the registry. If you look at the `index.php` file you will see this is allocated in there

// Cart
$registry->set('cart', new Cart($registry));

Problem

Im current trying to learn more about the core of OpenCart and how its classes actually work. Im also trying to advance my OOP skills in general as Im still learning in that area, so perhaps theres something obvious that Im not seeing. Im wondering how a controller file knows how to find the cart class (for example). E.g. In catalog/controller/checkout cart there is (obviously with code removed) ``` class ControllerCheckoutCart extends Controller { public function index() { $this->cart->update(); } } ``` The Controller class can be found in system/engine/controller.php `update()` can be found system/library/cart. I assumed that in the controller.php there would be a link to the cart class, or an object made from it. (Im basing that on the use of `$this->`). So how is the cart class actually found from the controller? Thank you

Original source