Overriding Controllers via Events in Opencart 4.x.x

196 Views Asked by At

I'm trying to figure out how to override a controller for building a custom theme in OpenCart 4. Obviously the documentation is extensive and I have gone through all of it and now I'm very proud of my decision to choose OpenCart 4, by far the best open source ecommerce platform available. So I can't go back on that decision obviously.

That aside I am attempting to override the common/header controller using the example in the opencart example theme plugin available in the original source. I tried setting an event before for that specific controller which triggers fine. In the header override function I attempt to change the route so that the system will use my custom controller but every time I run it it just goes ahead and uses the regular original controller.

Can anyone shed some light on what the issue might be? It seems to me like it should work based on the very detailed documentation available from the OpenCart developer(s?) for this new version.

Right now I'm registering the event on install:

        $event_data = [
            'code'        => 'oc_pif_theme_example',
            'description' => 'Pif Example theme extension controller override',
            'trigger'     => 'catalog/controller/common/header/before',
            'action'      => 'extension/oc_pif_theme_example/startup/theme_example.header_override',
            'status'      => 1,
            'sort_order'  => 0
        ];

        $this->load->model('setting/event');
        
        $this->model_setting_event->addEvent($event_data);

This is my header_override method:

public function header_override(string &$route, array &$args): void {

    $override = ['common/header'];

    if (in_array($route, $override)) {
        // Override the route to point to your new controller
        $route = 'extension/oc_pif_theme_example/' . $route;
        $this->log->write('header_override() final route: ' . $route);

    }

}

In my custom controller which is found in extension/oc_pif_theme_example/catalog/controller/common/header.php I have the index method with some logging to check that it actually runs and loading the twig file.

Anything that can point me in the right direction is appreciated. Thank you for your input.

0

There are 0 best solutions below