Search code examples
model-view-controlleropencartopencart2.xopencart-3

How can I pass parameters when loading my library in Opencart?


I need to pass parameters to my Opencart library class which is loaded using $this->load->library('MyLib'). The trouble is that the loader only accepts a single argument. I'd like to do something like this:

$this->load->library('MyLib', array('parameters') );

How can I pass an array of arguments to my library class when it's loaded?


Solution

  • The loader's library() method only allows a single argument: $route, but fortunately $this->registry is passed as a single argument to the library's constructor. To pass additional parameters you can simply assign them as properties to the registry class before loading your library like this:

    $params = [
        'param_1' => 'abc',
        'param_2' => 'def'
    ];
    $this->registry->set('MyLib_params', $params);
    
    // now load your library
    $this->load->library('MyLib');
    

    Then, you can access that property inside inside your library constructor like this:

    class MyLib {
        public function __constructor($registry) {
            $this->params = $registry->get('MyLib_params');
            // do stuff with $this->params
        }
    }
    

    Actually, you can access anything in the registry there as well which is useful for getting all kinds of data like config, session, cart, etc.