In my first web application when I used Zend, I didn’t write a single line of code in my models.
I’d only created models directory when I was doing necessary configuration. That was because I wasn’t aware what MVC is all about and was individually working on the application.
After switching to one of the best organization and finding a place in a team that was and is working on a large scale web application in Zend Framework, I really feel the test of MVC.
As I have now worked on Zend for about 7 months, I know where to put necessary code. The role of models in creating large scale application using any framework can never be ignored.
It will be a big mistake if developer place code related to business logic into controller instead of model.
I will recommend the following.
Make necessary configuration in your bootfile. If you want to connect to the database, write following code in your boot file.
‘database’ => array(
‘adapter’ => ‘Pdo_Mysql’,
‘params’ => array(
‘host’ => ‘localhost’,
‘username’ => ‘root’,
‘password’ => ‘’,
‘dbname’ => ‘database_name’
That’s it. You have now configured your application and can extend your model class from Zend_Db_Table, and all the functionality define in Zend_Db_Table will automatically be available to your class.
Now If you want to fetch, insert, delete data from database. Create a file in your model and put all the functionality in that file.
It will be better if you create separate model file-file in your model directory, for each table in your database.
If you have a table name users in your database, simply create users.php in your application/models directory and write the following code.
class Users extends Zend_Db_Table
This is your model class. You can now perform different functions like insert, update, delete on the user table with writing only few lines of code.
In your controller/action write
$users = new Users();
This two lines of code will now insert new row into your user table.
This line will update the row having id=2 with the specified values.
Will delete row from the users table with id=2;
All the above method become available to you when you extend your class from Zen_Db_Table.
While working in web applications you may need to fetch customize data from the database, so write function in your model classes instead of writing code in the controller and simply call your function.
To fetch data I will write in my model class, the following code
public function getUserData()
$select = $this->_db->select()
$results = $this->getAdapter()->fetchRow($select);
And then in my controller I will write
$users = new Users();
$userData = $users->getUserData();
This will return row as an array.
I can dump it as