7

I have a component ('com_foo') which has a model called 'foobar'. The class declaration is like this:

class FooModelbar extends JModelItem

This class has a public method called getFooBar().

I also have a system plugin called 'foobar'. I am trying to access the public method of the component from this plugin.

JLoader::register('FooModelBar', JPATH_SITE . '/components/com_foo/models/bar.php');
$foobarInstance = new FooModelBar();
$baz = $foobarInstance->getFoobar();

But I am getting some unrelated errors like 'Cannot redeclare function x' which is not even in the plugin or the component. And if I turn off the plugin or remove the JLoader::register line of code, the error disappears. So clearly I must be doing something wrong.

What is the 'correct' way to access a component's method from a system plugin?

1
  • Could you please post your code here?
    – itoctopus
    Jul 9, 2016 at 5:25

2 Answers 2

5

This will work with ease in Joomla 3.x

//load model
JModelLegacy::addIncludePath(JPATH_SITE . DIRECTORY_SEPARATOR . 'components' . DIRECTORY_SEPARATOR . 'com_foo' . DIRECTORY_SEPARATOR . 'models');

//get instance of model class, where class name will be fooModelBar
$model = JModelLegacy::getInstance('bar', 'fooModel');

//call model method
$baz = $model->getFoobar();
4

To call a model from anywhere inside Joomla you can use this method

//Load the Joomla Model framework
jimport('joomla.application.component.model');

//Load com_foo's foobar model. Remember the file name should be foobar.php inside the models folder
JModelLegacy::addIncludePath(JPATH_SITE.'/components/com_foo/models', 'FooModelBar');

//Get Instance of Model Object
$foobarInstance = JModelLegacy::getInstance('foobar', 'FooModelBar');

//Now you can call the methods inside the model
$baz = $foobarInstance->getFoobar();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.