Nov 27, 2010
admin

A first model definition

In the previous section, we wrote our indexAction which makes use of a FeedModel model. Like the controllers, the models are modelized by classes. Again, you can choose the filename you want to store the models, Simple MVC will find the model by itself. Despite, we follow a folder hierarchy and some standards to place each file in an appropriate folder. The models are places under business/{your-module-application}/models. So in our case business/front/models.
So lets create our FeedModel under that folder:

/**
 * Feed Model
 */
class FeedModel extends CoreModel
{
    /**
     * Table Name
     *
     * @var mixed  Defaults to 'feed'.
     */
    protected $_tableName = 'feed';
 
    /**
     * Table keys
     *
     * @var array  Defaults to array('id').
     */
    protected $_tableKeys = array('id');
 
    // public properties
    /**
     * Feed Name
     *
     * @var string  Defaults to null.
     */
    public $name = null;
 
    /**
     * Feed Url
     *
     * @var string  Defaults to null.
     */
    public $url = null;
 
    /**
     * Items to be shown
     *
     * @var int  Defaults to null.
     */
    public $itemsNumber = null;
}

As you notice, the two protected properties of the Feed model will specify the table name and the table keys. the following will specify the properties, (the fields in the table). At the current version, Simple MVC is still implementing the Active Record pattern, However, this is subject to change in latter version to implement another pattern which will allow to have some separation of the table definition from the model itself, and to allow dis-coupling column names with properties names.
You understand though that we need to have to create a table corresponding to the model. Here is the SQL :

CREATE TABLE IF NOT EXISTS `feed` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `url` varchar(255) NOT NULL,
  `itemsNumber` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 ;
 
// make some insert directly when you create your tables
INSERT INTO `feed` (`id`, `name`, `url`, `itemsNumber`) VALUES
(1, 'Anis berejeb', 'http://feeds.feedburner.com/AnisBerejeb', 5),
(2, 'Houssem Bensalem', 'http://www.hbensalem.com/feed/', 4);

This is all we need for the model, all the magic is here since the FeedModel extends the CoreModel. However, the FeedModel is the placeholder where you will do your Data related logic. For example if you need to write some specific methods to deal with the data and return a certain collection or a certain instance, it should be in the model and not in the controller. The controller has just to “ask” the model to give him the data needed.
So Let’s continue to have our working index page, let’s have a look at the view section.

1 Comment

Leave a comment