How to Call a Model from Another Model in Joomla!

WebTechRiser.com > Joomla 2.5 > How to Call a Model from Another Model in Joomla!

When developing a custom component using Joomla! Framework, according to its Model-View-Controller (MVC) design pattern, a model is generally used for a view.

But, in reality, much more data is used in custom components. As a result, the component becomes more complex quickly and its size increases. For this reason, one model has to use data from another existing model. This saves time as well as avoids repetitive code.

This tutorial shows an example of how to use a function of one of the models in a Joomla! component by calling the second model is shown along with the code example. Hopefully, any Joomla! developer can benefit from this code.

In my custom component “com_news”, I have a view for editing data in the administration area named, “New” (“administrator/components/com_news/views/new/tmpl/edit.php”).

  • I have created its model, named, “New” in “administrator/components/com_news/models/new.php”.
  • I want to use another model named, “gallery” (“administrator/components/com_news/models/gallery.php”) and call its “getGallery()” method from the “new” model.

Now, this model can be called either within or outside the ‘com_news as:

$galleryModel = $this->getInstance('Gallery', 'NewsModel');

Note: When I am inside a model, JModel class is defined already, so I need not include the path of other models. Thanks to Joomla’s MVC design pattern.

Now, I can call any function from that model using this instance, like:

$this->gallaeryList = $galleryModel->('Gallery');

These codes follow the coding standard of Joomla 3.x, which is supposed to work in Joomla 2.5 as well.

How do you call another model from a Joomla! model? I am especially calling upon you to share your code with me. Thank you for taking the time to read my blog.

Also read:  How to save component parameters to the database programmatically

Leave Your Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.