Joomla MVC – Load a model from anywhere!

Hello there!

It is good to reuse functionality whenever you can. Many think that there is a 1 to 1 relationship in regards to model and view, but this is not the case. In fact, the model can be called from anywhere. This means that you can quickly hook into functionality without duplicating code, which is always a good thing!

Let say for example that we have a component called com_foo and we want to access it’s items model from say a module (could be a plugin as well).

//first we import some help from the joomla framework

//Load com_foo's items model (notice we are linking to com_foo's model directory)
//and declare 'items' as the first argument. Note this is case sensitive and used to construct the file path.
JLoader::import( 'items', JPATH_ADMINISTRATOR . DS . 'components' . DS . 'com_foo' . DS . 'models' );

//Now instantiate the model object using Joomla's camel case type naming protocol.
$items_model = JModel::getInstance( 'items', 'FooModel' );

//Now that we have the item's model loaded, we can set its state
$items_model->setState( 'id', $myItemId );

//and use it's methods!


Sign up today to stay informed with industry news & trends