Web Frameworks - Workbook - Week 04

From mi-linux
Revision as of 12:11, 19 January 2010 by In9352 (talk | contribs)
Jump to navigationJump to search

Main Page >> Web Frameworks >> Workbook >> Workshop - week 04

Create a Model and Database Table

Before we get started, let's consider something: where will these classes live, and how will we find them? The default project we created instantiates an autoloader. We can attach other autoloaders to it so that it knows where to find different classes. Typically, we want our various MVC classes grouped under the same tree -- in this case, application/ -- and most often using a common prefix.

Zend_Controller_Front has a notion of "modules", which are individual mini-applications. Modules mimic the directory structure that the zf tool sets up under application/, and all classes inside them are assumed to begin with a common prefix, the module name. application/ is itself a module -- the "default" module. As such, let's setup autoloading for resources within this directory, giving them a prefix of "Default". We can do this by creating another bootstrap resource.

Step 1 - Set-up autoload

Zend_Application_Module_Autoloader provides the functionality needed to map the various resources under a module to the appropriate directories, and provides a standard naming mechanism as well. In our bootstrap resource, we'll instantiate this, and be done. The method looks like this:

// application/Bootstrap.php

// Add this method to the Bootstrap class:

    protected function _initAutoload()
    {
        $autoloader = new Zend_Application_Module_Autoloader(array(
            'namespace' => 'Default_',
            'basePath'  => dirname(__FILE__),
        ));
        return $autoloader;
    }

The final bootstrap class will look as follows:

class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
    protected function _initAutoload()
    {
        $autoloader = new Zend_Application_Module_Autoloader(array(
            'namespace' => 'Default',
            'basePath'  => dirname(__FILE__),
        ));
        return $autoloader;
    }

    protected function _initDoctype()
    {
        $this->bootstrap('view');
        $view = $this->getResource('view');
        $view->doctype('XHTML1_STRICT');
    }
}

Step 2 - Create your model class

Now, let's consider what makes up a guestbook. Typically, they are simply a list of entries with a comment, timestamp, and, often, email address. Assuming we store them in a database, we may also want a unique identifier for each entry. We'll likely want to be able to save an entry, fetch individual entries, and retrieve all entries. As such, a simple guestbook model API might look something like this:

// application/models/Guestbook.php

class Default_Model_Guestbook
{
    protected $_comment;
    protected $_created;
    protected $_email;
    protected $_id;

    public function __set($name, $value);
    public function __get($name);

    public function setComment($text);
    public function getComment();

    public function setEmail($email);
    public function getEmail();

    public function setCreated($ts);
    public function getCreated();

    public function setId($id);
    public function getId();

    public function save();
    public function find($id);
    public function fetchAll();
}

__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.

find() and fetchAll() provide the ability to fetch a single entry or all entries.

Now from here, we can start thinking about setting up our database.

Step 3 - Create database table

Let's create this simple table:

CREATE TABLE guestbook (
    id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
    email VARCHAR(32) NOT NULL DEFAULT 'noemail@test.com',
    comment TEXT NULL,
    created DATETIME NOT NULL
);

... and populate it with some test data:

INSERT INTO guestbook (email, comment, created) VALUES 
    ('ralph.schindler@zend.com', 
    'Hello! Hope you enjoy this sample zf application!', 
    DATETIME('NOW'));
INSERT INTO guestbook (email, comment, created) VALUES 
    ('foo@bar.com', 
    'Baz baz baz, baz baz Baz baz baz - baz baz baz.', 
    DATETIME('NOW'));

You can do this via "phpmyadmin": https://mi-linux.wlv.ac.uk/phpmyadmin/

If you haven't registered for a Mysql database yet, you can do so here: https://mi-linux.wlv.ac.uk/facilities/

Once you have created your Mysql database, simply add its connection details to your app.ini file:

Step 4 - initialize our Db resource

Then we need to initialize our Db resource. As with the Layout and View resource, we can provide configuration for the Db resource. In your application/configs/application.ini file, add the following lines in the appropriate sections:

[production]
resources.db.adapter       = "PDO_MYSQL"
resources.db.params.host   = "localhost"
resources.db.params.username   = "YOUR STUDENT NUMBER"
resources.db.params.password   = "YOUR DB PASSWORD"
resources.db.params.dbname = "dbYOUR STUDENT NUMBER"

[development : production]
resources.db.params.host   = "localhost"
resources.db.params.username   = "YOUR STUDENT NUMBER"
resources.db.params.password   = "YOUR DB PASSWORD"
resources.db.params.dbname = "dbYOUR STUDENT NUMBER"

[testing : production]
resources.db.params.host   = "localhost"
resources.db.params.username   = "YOUR STUDENT NUMBER"
resources.db.params.password   = "YOUR DB PASSWORD"
resources.db.params.dbname = "dbYOUR STUDENT NUMBER"

Now we have a fully working database and table for our guestbook application. Our next few steps are to build out our application code. This includes building a data source (in our case, we will use Zend_Db_Table), and a data mapper to connect that data source to our domain model. Finally we'll also create the controller that will interact with this model to both display existing entries and process new entries.