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? Commented Jul 9, 2016 at 5:25

3 Answers 3

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(); 
0

For Joomla 4+ use the new way to do it:

use Joomla\CMS\Factory; $model = Factory::getApplication()->bootComponent('com_content')->getMVCFactory() ->createModel('Articles', 'Site', ['ignore_request' => true]); $articles = $model->getItems(); 

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.