Search code examples
phpzend-frameworkzend-db

zend database mapper best way?


Hi what will be best way to fetch a data from databse in zend framework based application? is there any difference between mapper and DbTable files, and also it would be great if hv a simple example to demostrate. Thanks


Solution

  • You should have to write a library first before use mapper which will be easier for you to call and defined new. Below is one of good way to define mapper based db table with the library.

    in model folder you need to have DbTable and mapper folder. Inside DbTable create User.php and in mapper create an UserMapper.php file. Also inside the model folder itself you have to create User.php file.Below is sample code

    DbTable>User.php

    <?php
     class Application_Model_DbTable_Users extends Zend_Db_Table_Abstract
     {
     protected $_name = 'users';
     }
     ?>
    

    mapper>UserMapper.php

    <?php
     class Application_Model_Mapper_UserMapper extends Zc_Model_BaseMapper
     {
      public function __construct()
      {
        $this->setDbTable('Application_Model_DbTable_Users');
      }
    
      public function find($userid Application_Model_User $user)
      {
      // sql will go here
      }
    

    model>User.php

    class Application_Model_User extends Zc_Model_Base
    {
      protected $_userId;
      protected $_userName;
    
      public function setUserId($userId)
      {
        $this->_userId = $userId;
        return $this;
      }
      publc function getUserId()
      {
        return $this->_userId;
      }
    
      public function toArray()
      {
        $data = array(
          'user_id' => getUserId();
         )
        return $data
      }
    

    Hope this will help you ;-)