Zend framework tutorial, build your Blog

Create application/Models/DbTable/Users.php

<?php
class Model_DbTable_Users extends Zend_Db_Table_Abstract
{
    protected $_name = 'users';
    public function findCredentials($username, $pwd)
    {
        $select = $this->select()->where('username = ?', $username)
            ->where('password = ?', $this->hashPassword($pwd));
        $row = $this->fetchRow($select);
        if($row) {
            return $row;
        }
        return false;
    }
    protected function hashPassword($pwd)
    {
        return md5($pwd);
    }
}

Create application/Models/DbTable/Comments.php

<?php
class Model_DbTable_Comments extends Zend_Db_Table_Abstract
{
    protected $_name = 'comments';
    public function getComments( $postid ) 
    {
        $result = $this->fetchAll( "post_id = '$postid'"  );
        return $result->toArray();
    }
    public function saveComment( $commentForm )
    {
        $data = array('post_id' => $commentForm['id'] ,
                'Description' => $commentForm['comment'],
                'Name' => $commentForm['name'],
                'Email' => $commentForm['email'],
                'Webpage' => $commentForm['webpage'] );
        $this->insert($data);
    }
}

 Now lets create a login form in /application/forms/Login.php directory . 

<?php
class Form_Login extends Zend_Form
{
    public function __construct()
    {
        parent::__construct($options);
        $this->setName('UserLogin');
        $username = new Zend_Form_Element_Text('username');
        $username->setLabel('User Name')
                ->setRequired(true)
                ->addFilter('StripTags')
                ->addFilter('StringTrim')
                ->addValidator('NotEmpty');
        $pass = new Zend_Form_Element_Password('pass');
        $pass->setLabel('Password')
                ->setRequired(true)
                ->addFilter('StripTags')
                ->addFilter('StringTrim')
                ->addValidator('NotEmpty');
        $submit = new Zend_Form_Element_Submit('submit');
        $redirect = new Zend_Form_Element_Hidden('redirect');
        $submit->setAttrib('id', 'submitbutton');
        $this->addElements( array ( $username, $pass, $submit));
    }
}

Create a form for posting and commenting

application/forms/posts.php

<?php
class Form_Post extends Zend_Form
{
    public function __construct()
    {
        parent::__construct($options);
        $this->setName('Posts');
        $id = new Zend_Form_Element_Hidden('id');
        $title = new Zend_Form_Element_Text('Title');
        $title->setLabel('Title')
                ->setRequired(true)
                ->addFilter('StripTags')
                ->addFilter('StringTrim')
                ->addValidator('NotEmpty');
        $description = new Zend_Form_Element_Textarea('Description');
        $description->setLabel('Description')
                ->setRequired(true)
                ->setAttrib('rows',20)
                ->setAttrib('cols',50)
                ->addFilter('StripTags')
                ->addFilter('StringTrim')
                ->addValidator('NotEmpty');
        $submit = new Zend_Form_Element_Submit('submit');
        $submit->setAttrib('id', 'submitbutton');
        $this->addElements( array( $id, $title, $description, $submit ));
    }
}

Create a comments form application/forms/Comments.php for adding comments

<?php
class Form_Comments extends Zend_Form
{
    public function __construct()
    {
        $acl = new Model_Acl();
        $identity = Zend_Auth::getInstance()->getIdentity();
        /*
        * Check whether they have permission to add comments
        */
        if( Zend_Auth::getInstance()->hasIdentity()
        && $acl->isAllowed( $identity['role'] ,'comments','add') ) {
            parent::__construct($options);
            $this->setName('Comments');
            $id = new Zend_Form_Element_Hidden('id');
            $name = new Zend_Form_Element_Text('name');
            $name->setLabel('Your Name')
            ->setRequired(true)
            ->addFilter('StripTags')
            ->addFilter('StringTrim')
            ->addValidator('NotEmpty');
            $email = new Zend_Form_Element_Text('email');
            $email->setLabel('Email')
            ->setRequired(true)
            ->addFilter('StripTags')
            ->addFilter('StringTrim')
            ->addValidator('NotEmpty');
            $webpage = new Zend_Form_Element_Text('webpage');
            $webpage->setLabel('Webpage')
            ->setRequired(true)
            ->addFilter('StripTags')
            ->addFilter('StringTrim')
            ->addValidator('NotEmpty');
            $comment = new Zend_Form_Element_Textarea('comment');
            $comment->setLabel('Comments')
            ->setRequired(true)
            ->setAttrib('rows',7)
            ->setAttrib('cols',30)
            ->addFilter('StripTags')
            ->addFilter('StringTrim')
            ->addValidator('NotEmpty');
            $submit = new Zend_Form_Element_Submit('submit');
            $submit->setAttrib('id', 'submitbutton');
            $this->addElements( array ($id, $name, $email, $webpage, $comment, $submit));
        }
    }
}

Create application/Models/Acl.php

<?php
class Model_Acl extends Zend_Acl 
{
    public function __construct() 
    {
        /*
         *  Add a new role called "guest"
         *  Guest can view contents of the site 
         */
        $this->addRole(new Zend_Acl_Role('guest'));
        /* 
         * Add a role called user, which inherits from guest
         * Users can post comments in site
         */
        $this->addRole(new Zend_Acl_Role('user'), 'guest');
        /* 
         * Add a role called blogger, which inherits from user
         * Bloggers can post contents
         */
        $this->addRole(new Zend_Acl_Role('blogger'), 'user');
        /*
         * Add a role for admin which inherits blogger
         * With every privilages
         */
        $this->addRole(new Zend_Acl_Role('admin'), 'blogger');
        //Add a resource called posts
        $this->add(new Zend_Acl_Resource('posts'));
        //Add a resource called edit, which inherits posts
        //$this->add(new Zend_Acl_Resource('edit'), 'posts');
        //Add a resource called edit
        //$this->add(new Zend_Acl_Resource('add'), 'posts');
        //Finally, we want to allow guests to view pages
        $this->allow('guest', 'posts', 'view');
        // Bloggers can add, edit posts
        $this->allow('blogger', 'posts', 'edit');
        $this->allow('blogger', 'posts', 'add');
    }
}

Create application/Models/AuthAdapter.php

<?php
class Model_AuthAdapter implements Zend_Auth_Adapter_Interface
{
    protected $username;
    protected $password;
    protected $user;
    public function __construct($username, $password) {
        $this->username = $username;
        $this->password = $password;
        $this->user = new Model_DbTable_Users();
    }
    public function authenticate()
    {
        $match = $this->user->findCredentials($this->username, $this->password);
        //var_dump($match);
        if(!$match) {
            $result = new Zend_Auth_Result(Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID, null);
        } else {
            $user = current($match);
            $result = new Zend_Auth_Result(Zend_Auth_Result::SUCCESS, $user);
        }
        return $result;
    }
}

Create application/views/helpers/BaseUrl.php

<?php
class Zend_View_Helper_BaseUrl {
    function baseUrl() {
        $fc = Zend_Controller_Front::getInstance();
        return $fc->getBaseUrl();
    }
}
?>

Create application/views/helpers/LinkTo.php

<?php
class Zend_View_Helper_LinkTo
{
    protected static $baseUrl = null;
    public function linkTo($path)
    {
        if (self::$baseUrl === null) {
            $request = Zend_Controller_Front::getInstance()->getRequest();
            $root = '/' . trim($request->getBaseUrl(), '/');
            if ($root == '/') {
                $root = '';
            }
            self::$baseUrl = $root . '/';
        }
        return self::$baseUrl . ltrim($path, '/');
    }
}

Anonymous's picture

Thanks for the answer but nothing has changed...i point by browser to blog/pubic but i found only a blankpage...

hari's picture

I guess , something went wrong . May be you want to look whether all errors can be thrown from PHP . I mean initialise the display_errors and E_ALL .

Have you tried the Quick start? If you have tried that I hope that may have resolved most of the problems.

Thanks again.

Anonymous's picture

In the file: application/views/scripts/posts/view.phtml you have litered the code with open and close PHP tags.
Why do it that way?
In my opinion, the code be easier to read and cleaner if there was only one set of PHP tags. Just echo the HTML where required?

hari's picture

phtml file contains less php codes . Its the view, so the designers can quickly understand and change.
If you have once used smarty you would have understood. This is why we keep model in one place , controller in another and view in another . Else I would have places all in one :) . There are lots more benefits for MVC :). You may want to explore ;).

Anonymous's picture

This would get me excited if I'd seen some screenshots or heard some information about it, but at the moment, I really am not bothered about it at all.

Anonymous's picture

Hi,
The error message I get now is:

An error occurred
Application error

can you help me?
where could it possibly have been wrong?

Anonymous's picture

I have also tried it and it was working perfectly.
I have build a complete blog with the help of this tutorial.

Powered by Drupal, an open source content management system