I have created a custom component in Joomla 2.5
. In this component I want to fetch all the user 's are available in com_users
.For this I want you to know, How can i use com_users
model class in to my component. Any one have suggestion's to how to do it.
Depending on where you want use the model you can simply ask Joomla! to load it for you.
In a JController
class or sub-class you can call getModel
passing in the model name and the components prefix...
e.g.
JModel::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_users/models/');
$model = $this->getModel($name = 'User', $prefix = 'UsersModel');
It may be necessary to add the path of the external model you want to load using JModel::addIncludePath()
as show above.
Or if you're sure of the model name and the class prefix you could use JModel
's getInstance()
to create the desired model object... e.g.
$model = JModel::getInstance('User', 'UsersModel');
Alternatively in a view you could:
$myModel = $this->getModel('myOtherModel');
$this->setModel($myModel);
N.B. In the first line we're passing our desired models name, normally you call getModel
without any params to load the default model for your components view controller. In the second line, as we're only passing the model to setModel()
it won't make it the default model the view uses.
When we want to use our model objects later on we can specify which we want to use like this:
$item = $this->get('Item');
$otherItem = $this->get('Item', 'myOtherModel' );
The first line uses the view's default model (because we have specified one in the optional parameter). The second line uses the getItem()
from myOtherModel
.
That's all works because JView
(in libraries/joomla/application/view.php
) has these methods:
/**
* Method to get the model object
*
* @param string $name The name of the model (optional)
*
* @return mixed JModel object
*
* @since 11.1
*/
public function getModel($name = null)
{
if ($name === null)
{
$name = $this->_defaultModel;
}
return $this->_models[strtolower($name)];
}
/**
* Method to add a model to the view. We support a multiple model single
* view system by which models are referenced by classname. A caveat to the
* classname referencing is that any classname prepended by JModel will be
* referenced by the name without JModel, eg. JModelCategory is just
* Category.
*
* @param JModel &$model The model to add to the view.
* @param boolean $default Is this the default model?
*
* @return object The added model.
*
* @since 11.1
*/
public function setModel(&$model, $default = false)
{
$name = strtolower($model->getName());
$this->_models[$name] = &$model;
if ($default)
{
$this->_defaultModel = $name;
}
return $model;
}