Models are intended to handle a component's data processing. This usually although not exclusively involves storing and retrieving data from the database. Let's take a look at how a model could be used to retrieve records from the database so that they can be displayed in a view.
First, we're going to create models folder into our Joomla installation in the com_noidacity folder. Once you have created models folder go inside and create malls.php file inside. So this is a model file and add the following code.
We have a class here defined and it's called NoidaCityModelMalls and that follows the convention of the component name model and the name of the model. It's extending the JModelList class. JModel List is specifically designed for pulling a list of records from the database, so that they can be displayed in the front-end.
Next, we define the getListQuery function. This function is one that JModelList is going to look for and it's going to call this function and get back a query object, so that it can run it against the database.
If you call the getListQuery function that just comes with JModelList by default, you get back a database query object that's fresh and ready to go. That's exactly what we want.
Once we have that query object, we call the select, and from, and where functions, so that we can build our database query. So we just want the mall_name from all the published malls in noidacity.
Once we've built that query object, we just return it. So this is all we need for our model to get the mall_name from all of the published malls in the database.
In order to display those malls, we need to make a few adjustments to our malls view. So go to Views, and malls, and edit view.html.php. Add the following lines of code
Notice that this is a get method for JView and it's not the actual get method that's in the model. This is because Joomla does not let JView directly touch the model. It does this abstraction to make sure that we're not trying to pull anything directly from the model that we shouldn't be doing.
So after saving the view.html.php file, we need to edit the layout file as well so that it actually displays the records.
So go into tmpl, and open up default.php and add the following code:
and now with this in place, we can load this view in the front-end.
Go to index.php?option=com_noidacity and then view=malls. So now you'll notice in addition to the header that we had before, all the database code is in the model while all of the display code is right here in the View. That way, we don't have the two mixing with each other and if we want to adjust the view, we don't have to worry about disturbing the model and breaking something.
So models allow you to interact with the database completely separate from views. Because of the separation, you can work on HTML output in the View without worrying about accidentally breaking your database queries.