I am still learning to make a Joomla component, but I have run into a situation which I cannot find the answer to in any tutorial or book I have read so far. I have a Model (in models/weather.php) which has a method getData(). This method is called from View (in views/view.html.php) and this gets a range of records from my database. This range of records is then iterated through in my layout (views/tmpl/default.php) using a foreach loop, something like this:
if ($this->item) {
foreach ($this->item as $item) {
//...
}
}
What I need to do is at the point of the comment (//...) I want to retrieve some other record from another table based on the value of $item->id. My question is how do I do this accord开发者_开发百科ing to best practice? I suppose I could just open up the database right there and get the data I need, but I am suspecting that in a MVC based program I need to put this query in a function or method? Where do I put this and how do I access it? A link to an example would be much appreciated.
ANSWER: I am such an idiot. Obviously I can just call any method from the view in my layout and in that method I can access my Model (where I can create the lookup function). Sometimes my mind is (still) too procedural to simply 'see' OOP.
It is bad practice to process data in the layout(default.php). Layout should only display already retrieved and processed data from model via view(view.html.php). Why don't you add another method to your model and call that method from getData
? It would be much better.
you can write a method in your other model from where you want to pull data like getMyItem(). Then in your view you would need to get the model like
$model = & JModel::getInstance('ModelName','ComponentNameModel'); //it will look for ComponentNameModelModelName
$myitem = $model->getMyItem($item->id);
Write logic to get Myitem in model's method
精彩评论