Skip to main content

By clicking Submit, you agree to the developerWorks terms of use.

The first time you sign into developerWorks, a profile is created for you. Select information in your profile (name, country/region, and company) is displayed to the public and will accompany any content you post. You may update your IBM account at any time.

All information submitted is secure.

  • Close [x]

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerworks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

By clicking Submit, you agree to the developerWorks terms of use.

All information submitted is secure.

  • Close [x]

Understanding the Zend Framework, Part 2: Model-View-Controller and adding a database

Building the perfect reader

Nicholas Chase (ibmquestions@nicholaschase.com), Consultant, Backstop Media
Nicholas Chase has been involved in Web-site development for companies such as Lucent Technologies, Sun Microsystems, Oracle, and the Tampa Bay Buccaneers. He has been a high school physics teacher, a low-level radioactive waste facility manager, an online science fiction magazine editor, a multimedia engineer, an Oracle instructor, and the chief technology officer of an interactive communications company. He is the author of several books, including XML Primer Plus (Sams).
Tracy Peterson (tracy@tracypeterson.com), Freelance Writer, Freelance Developer
Tracy Peterson has worked as an IT project manager and Web developer since 1997 and most recently worked as an operations program manager on MSN Search at Microsoft. He is based in San Francisco.

Summary:  This "Understanding the Zend Framework" series chronicles the building of an online feed reader, Chomp, while explaining the major aspects of using the open source PHP Zend Framework. Part 1 discusses the goals behind the Zend Framework, including easy-to-use components and an architecture based on the Model-View-Controller (MVC) pattern. In Part 2, you will see how to use the Zend Framework to create the beginnings of the online feed reader, Chomp, creating a form and adding information to a database while getting to know the MVC pattern.

View more content in this series

Date:  24 Jan 2011 (Published 11 Jul 2006)
Level:  Intermediate PDF:  A4 and Letter (601 KB | 45 pages)Get Adobe® Reader®

Activity:  141037 views
Comments:  

Using the registry

So far, you've covered how to make all of this work, but there's one more feature you need to look at that will make your life easier: the Zend_Registry.

What is the Zend_Registry?

The Zend_Registry is a place to store all of those objects you're going to use repeatedly in your application. For example, if you have a view that you use in multiple places, storing it here will enable you to have a single instance you can change without having to find all of the instances throughout replication.

The registry can only store objects and stores them with a string value name by which you can later retrieve them. You may not remove an object from the registry, but understand that it exists only in the context of your current request, anyway. It is not a means for achieving persistent storage of objects, but, rather, a way to avoid storing them in session variables.

In your case, you can see it in action by storing the database connection in the registry, avoiding the necessity of recreating it every time you want to access the database.


Registering an object

Because all requests flow through the index.php file, that's the most likely place for us to create the database connection and register (see Listing 27).


Listing 27. Creating the database connection
                    
<?php

require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Db');
Zend_Loader::loadClass('Zend_Controller_Front');
Zend_Loader::loadClass('Zend_Registry');

$params = array(
             'host' => 'localhost',
             username' => 'chompuser',
             'password' => 'chomppassword',
             dbname' => 'chomp'
             );
$db = Zend_Db::factory('Pdo_Mysql', $params);
Zend_Registry::set('db', $db);
$baseURL = str_replace('/index.php','/',$_SERVER['PHP_SELF']);
Zend_Registry::set('baseURL', $baseURL);

$front = Zend_Controller_Front::getInstance();
$front->setBaseUrl($baseURL);
$front->setControllerDirectory('../application/controllers');
$front->setParam('noViewRenderer', true);
$front->dispatch();

?>

Here, you simply create the database connection as usual, adding it to the registry using the register() function and assigning it a name of DB. Now, if you need to change a username, password, or other information, simply change it here, and you're done. You will probably want to put this information in a less-vulnerable file and simply include it.

Accessing the registered object

Once the database connection has been registered, you can access it easily. At the moment, the only file that uses the database is the UserController (see Listing 28).


Listing 28. Accessing the registry
                    
<?php
require_once 'Zend/Db.php';

Zend_Loader::loadClass('Zend_Controller_Action');
Zend_Loader::loadClass('Zend_View');

class UserController extends Zend_Controller_Action
{

...
    
    function authenticateAction()
    {
        $DB = Zend_Registry::get('db');

        $select = $DB->select();
        $select->from('users', '*');
        $select->where('Username = ?', $_POST['username']);
        $select->where('Password = ?', $_POST['password']);
        $sql = $select->__toString();

        $rowsFound = $DB->fetchAll($select);
        if (isset($rowsFound[0]['username']))
        {
           session_start();
           $_SESSION['RSS_SESSION'] = session_id();
           $_SESSION['firstname'] = $rowsFound[0]['firstname'];
           $_SESSION['username'] = $rowsFound[0]['username'];

           echo "Login successful. Please <a href='/'>continue</a>.";
        }
        else
        {
           echo "Login information incorrect. \
           Please <a href='/user/login'>try again</a>.";
        }

    }

    function logoutAction()
    {
        echo 'This is the logoutAction.';
    }
    
    function registerAction()
    {
        $view = new Zend_View();
        $view->setScriptPath('../application/views/');
        echo $view->render('register.php');
    }

    function createAction()
    {
        $DB = Zend_Registry::get('db');

        $row = array(
            'FirstName' => $_POST['fName'],
            'LastName' => $_POST['lName'],
            'EmailAddress' => $_POST['email'],
            'Username' => $_POST['user'],
...

Notice that all you have done here is replace the database connection information with a call to the registry asking for the object reregistered under the string DB. Once you have the object, you use it just as you used it before.

7 of 11 | Previous | Next

Comments



static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Open source
ArticleID=132768
TutorialTitle=Understanding the Zend Framework, Part 2: Model-View-Controller and adding a database
publish-date=01242011
author1-email=ibmquestions@nicholaschase.com
author1-email-cc=
author2-email=tracy@tracypeterson.com
author2-email-cc=