Zend framework 1 article

Home >> Zend framework 1 >>

  Zend framework 1 CRUD operations part - 2

This article will explain you about the CRUD operations of Zend framework 1 in details include topics such as Model and Database Table.

Before we move to Model and Database Table, Let's create "blog" table.

CREATE TABLE `zf1app_db`.`blog`(
  `id` INT(11) NOT NULL AUTO_INCREMENT,
  `title` VARCHAR(250) NOT NULL,
  `description` TEXT NOT NULL,
  `created_at` DATETIME NOT NULL,
  `updated_at` TIMESTAMP ON UPDATE CURRENT_TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY(`id`)
) ENGINE = InnoDB;

Insert some record in this table.

INSERT INTO
  `blog`(
    `title`,
    `description`,
    `created_at`,
    `updated_at`
  )
VALUES(
  'blog test title 1',
  'blog test description 1',
  '2016-09-05 08:23:00',
  CURRENT_TIMESTAMP
),(
  'blog test title 2',
  'blog test description 1',
  '2016-09-05 08:24:00',
  CURRENT_TIMESTAMP
);

Db Table
We'll use a Table Data Gateway to connect to our data source; Zend_Db_Table provides this functionality. To get started, lets create a Zend_Db_Table-based table class. Just as we've done for layouts and the database adapter in previous article, using the command create db-table. This takes minimally two arguments, the name by which you want to refer to the class, and the database table it maps to.

Table Data Gateway An object that acts as a Gateway to a database table. One instance handles all the rows in the table.

C:\wamp\www\zf1app>zf create db-table BlogDbTable blog
Creating a DbTable at C:\wamp\www\zf1app/application/models/DbTable/BlogDbTable.php
Updating project profile 'C:\wamp\www\zf1app/.zfproject.xml' 

Looking at your directory tree, you'll now see that a new directory, application/models/DbTable/, was created, with the file BlogDbTable.php. If you open that file, you'll see the following contents:

class Application_Model_DbTable_BlogDbTable extends Zend_Db_Table_Abstract
{
    protected $_name = 'blog';
}

Data Mapper
Data Mapper A layer of Mappers that moves data between objects and a database while keeping them independent of each other and the mapper itself.

Now let's create a Data Mapper. A Data Mapper maps a domain object to the database. In our case, it will map our model, Application_Model_Blog, to our data source, Application_Model_DbTable_BlogDbTable. A typical API for a data mapper is as follows:

C:\wamp\www\zf1app>zf create model BlogMapper
Creating a model at C:\wamp\www\zf1app/application/models/BlogMapper.php
Updating project profile 'C:\wamp\www\zf1app/.zfproject.xml'

Now, edit the class Application_Model_BlogMapper found in application/models/BlogMapper.php to read as follows:

class Application_Model_BlogMapper
{

    protected $_dbTable;

    /**
     * Set DbTable.
     * @param type $dbTable
     * @return \Application_Model_BlogMapper
     * @throws Exception
     */
    public function setDbTable($dbTable)
    {
        if (is_string($dbTable)) {
            $dbTable = new $dbTable();
        }
        if (!$dbTable instanceof Zend_Db_Table_Abstract) {
            throw new Exception('Invalid table data gateway provided');
        }
        $this->_dbTable = $dbTable;
        return $this;
    }

    /**
     * Get DbTable.
     * @return type
     */
    public function getDbTable()
    {
        if (null === $this->_dbTable) {
            $this->setDbTable('Application_Model_DbTable_BlogDbTable');
        }
        return $this->_dbTable;
    }

    /**
     * Save blog topic.
     * @param Application_Model_Blog $blog
     */
    public function saveTopic(Application_Model_Blog $blog)
    {
        $data = array(
            'title' => $blog->getTitle(),
            'description' => $blog->getDescription(),
            'created_at' => date('Y-m-d H:i:s'),
        );

        if (null == ($id = $blog->getId())) {
            unset($data['id']);
            return $this->getDbTable()->insert($data);
        } else {
            return $this->getDbTable()->update($data, array('id = ?' => $id));
        }
    }

    /**
     * Fetch individual blog topics.
     * @param type $id
     * @param Application_Model_Blog $blog
     * @return type
     */
    public function findTopic($id, Application_Model_Blog $blog)
    {
        $result = $this->getDbTable()->find($id);
        if (0 == count($result)) {
            return;
        }
        $row = $result->current();
        $blog->setId($row->id)
                ->setTitle($row->title)
                ->setDescription($row->description)
                ->setCreatedat($row->created_at)
                ->setUpdatedat($row->updated_at);

        return $row;
    }

    /**
     * Fetch all blog topics.
     * @return \Application_Model_Blog
     */
    public function fetchAllTopics()
    {
        $resultSet = $this->getDbTable()->fetchAll();
        $entries = array();
        foreach ($resultSet as $row) {
            $entry = new Application_Model_Blog();
            $entry->setId($row->id)
                    ->setTitle($row->title)
                    ->setDescription($row->description)
                    ->setCreatedat($row->created_at)
                    ->setUpdatedat($row->updated_at);
            $entries[] = $entry;
        }

        return $entries;
    }

    /**
     * Delete blog topic.
     * @param type $id
     * @return type
     */
    public function deleteTopic($id)
    {
        return $this->getDbTable()->delete("id = $id");
    }

}

find() and fetchAll() provide the ability to fetch a single entry or all entries, while save() takes care of saving an entry to the data store.

Now it's time to create our model class. We'll do so, once again, using the zf create model command:

C:\wamp\www\zf1app>zf create model Blog
Creating a model at C:\wamp\www\zf1app/application/models/Blog.php
Updating project profile 'C:\wamp\www\zf1app/.zfproject.xml'

Now, edit the class Application_Model_Blog found in application/models/Blog.php to read as follows:

class Application_Model_Blog
{

    protected $_id;
    protected $_title;
    protected $_description;
    protected $_created_at;
    protected $_updated_at;

    public function __construct(array $opti
    {
        if (is_array($options)) {
            $this->setOptions($options);
        }
    }

    public function __set($name, $value)
    {
        $method = 'set' . $name;
        if (('mapper' == $name) || !method_exists($this, $method)) {
            throw new Exception('Invalid guestbook property');
        }
        $this->$method($value);
    }

    public function __get($name)
    {
        $method = 'get' . $name;
        if (('mapper' == $name) || !method_exists($this, $method)) {
            throw new Exception('Invalid guestbook property');
        }
        return $this->$method();
    }

    public function setOptions(array $options)
    {
        $methods = get_class_methods($this);
        foreach ($options as $key => $value) {
            $method = 'set' . ucfirst($key);
            if (in_array($method, $methods)) {
                $this->$method($value);
            }
        }
        return $this;
    }

    public function setId($id)
    {
        $this->_id = (int) $id;
        return $this;
    }

    public function getId()
    {
        return $this->_id;
    }

    public function setTitle($title)
    {
        $this->_title = (string) $title;
        return $this;
    }

    public function getTitle()
    {
        return $this->_title;
    }

    public function setDescription($description)
    {
         $this->_descripti $description;
        return $this;
    }

    public function getDescription()
    {
        return $this->_description;
    }

    public function setCreatedat($ts)
    {
        $this->_created_at = $ts;
        return $this;
    }

    public function getCreatedat()
    {
        return $this->_created_at;
    }

    public function setUpdatedat($ts)
    {
        $this->_updated_at = $ts;
        return $this;
    }

    public function getUpdatedat()
    {
        return $this->_updated_at;
    }

}

__get() and __set() will provide a convenience mechanism for us to access the individual entry properties, and proxy to the other getters and setters. They also will help ensure that only properties we whitelist will be available in the object.

Write your comment now