Hi everyone,

Here I am again. Yesterday a friend asked me how to create the basics CRUD (Create, Release, Update, Delete) operations using Zend Framework. As everybody now, a basic CRUD it's a good way to understand some framework's resources to a new ZF developer. As he is a newbie with Zend Framework, the example will be simpler, but complete.

I think this example resumes a lot of things of a basic usage of Zend Framework, like controllers, models - not exactly ;-), views and the magic Zend_Form, with form validation, filters and more.

Our application context will be a simple Blog using MySQL as database. Why blog again? Because it's simple to understand, just it. Our blog application will have just the posts table, to show only the CRUD funcionallity. Comments and files can be reason to a future post.

We won't worry about CSS or visual effects, even less Javascript or Ajax . It's a simple post to explain a basic operation with the framework. Another resources will be subject to a new post. Let's go!

Creating the Blog project

We'll create the new blog project using the zf command line. For details using the command line see Using Zend_Tool On The Command Line.

zf create project blog

Download Zend Framework and copy the ZendFramework-1.11.8-minimal/library/Zend folder to your library folder, inside the Blog project.

You can share a Zend Framework folder just adding a new include_path inside index.php.

Configuring the database on the Bootstrap.php file

I don't like much configuration files. So, I prefer to setup the database on my Bootstrap.php file. Let's go.

PS: More about Bootstrap.php file.

<?php

/**
* application/Bootstrap.php  
*/  
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap  
{  

    protected function _initDatabase()  
    {  
        $adapter = Zend_Db::factory('pdo\_mysql', array(  
            'host' => 'localhost',  
            'username' => 'root',  
            'password' => '',  
            'dbname' => 'blog',  
            'charset' => 'utf8'

            /**  
            * Some options  
            * 'port' => '3307',  
            *'unix_socket' => '/tmp/mysql2.sock'  
            */  
        ));  
        Zend_Db_Table_Abstract::setDefaultAdapter($adapter); // setting up the db adapter to DbTable  
    }  

}

Creating the Post DbTable (like a model)

What is DbTables and how it works?

junior-mb:basic_crud juninhogr$ zf create db-table posts  
Please provide a value for $actualTableName  
zf> posts  
Note: The canonical model name that is used with other providers is "Posts"; not "posts" as supplied  
Creating a DbTable at /Library/WebServer/Documents/blog_posts/basic_crud/application/models/DbTable/Posts.php  
Updating project profile '/Library/WebServer/Documents/blog_posts/basic_crud/.zfproject.xml'

Setting up AutoLoader and some IncludePaths

To load DbTable (models) easier, let's configure the ZF AutoLoader and add the models folder to the PHP include_path.

<?php

/**
 * application/Bootstrap.php  
 */  

class Bootstrap extends Zend\_Application\_Bootstrap_Bootstrap  
{  
    public function _initAutoloader()  
    {  
        $loader = Zend\_Loader\_Autoloader::getInstance();  
        $loader->setFallbackAutoloader(true);  
    }

    protected function _initDatabase()  
    {  
        // ...  
    }  
}

Take a look at 12 and 17 lines.

<?php

/**
 * public/index.php  
 */

// Define path to application directory  
defined('APPLICATION_PATH') || define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application'));

// Define application environment  
defined('APPLICATION_ENV') || define('APPLICATION_ENV', (getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV') : 'development')); // change to development now

// Ensure library/ is on include_path  
set_include_path(implode(PATH_SEPARATOR, array(  
    realpath(APPLICATION_PATH . '/../library'),  
    realpath(APPLICATION_PATH . '/models/DbTable'), // we will just call 'new Posts()'  
    get_include_path(),  
)));

/** Zend_Application */  
require_once 'Zend/Application.php';

// Create application, bootstrap, and run  
$application = new Zend_Application(  
    APPLICATION_ENV,  
    APPLICATION_PATH . '/configs/application.ini'  
);  

$application->bootstrap()->run();

Let's change our Post class name to just Posts, at line 5.

<?php

/**
 * application/models/DbTable/Posts.php  
 */  

class Posts extends Zend_Db_Table_Abstract  
{  
    protected $_name = 'posts';  
    /**  
    * Our posts' primary key is just 'id'.  
    * If you have another name to that field just use this line below:  
    * protected $_primary = 'post_id';  
    */

}

SQL Dump

First we created the database named 'blog'. The SQL code below is the result of a Sequel Pro exportation feature.

# Dump of table posts  
# ------------------------------------------------------------

CREATE TABLE `posts` (  
    `id` int(11) unsigned NOT NULL AUTO_INCREMENT,  
    `title` varchar(120) DEFAULT NULL,  
    `category` varchar(100) DEFAULT NULL,  
    `body` text,  
    `created` datetime DEFAULT NULL,  
    `updated` datetime DEFAULT NULL,  
    PRIMARY KEY (`id`)  
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Getting the Post form using Zend_Form

Let's create a Zend_Form to represent our Posts model.

<?php

/**
 * controllers/PostsController.php  
 */  

class PostsController extends Zend_Controller_Action  
{  
    public function getForm()  
    {  
        $title = new Zend_Form_Element_Text('title');  
        $title->setLabel('Title')  
            ->setDescription('Just put the post title here')  
            ->setRequired(true) // required field  
            ->addValidator('StringLength', false, array(10, 120)) // min 10 max 120  
            ->addFilters(array('StringTrim'));

        $category = new Zend_Form_Element_Select('category');  
        $category->setLabel('Category')  
            ->setDescription('Select the post category')  
            ->setRequired(true)  
            ->setMultiOptions(array(  
                '' => ':: Select a category',  
                'php' => 'PHP',  
                'database' => 'Database',  
                'zf' => 'Zend Framework'  
                // ... more categories if you want  
            ))  
            ->addFilters(array('StringToLower', 'StringTrim')); // force to lowercase and trim

        $body = new Zend_Form_Element_Textarea('body');  
        $body->setLabel('Post')  
            ->setRequired(true)  
            ->setDescription('Your text. HTML tags aren
<h3>Starting to create the <em>Add</em> feature</h3>
<p>Let's first show the form in view file.</p>


<div class="highlight"><pre><code class="language-php" data-lang="php"><span class="o">&lt;?</span><span class="nx">php</span> 

<span class="sd">/**</span>
<span class="sd"> * controllers/PostsController.php  </span>
<span class="sd"> */</span>  

<span class="k">class</span> <span class="nc">PostsController</span> <span class="k">extends</span> <span class="nx">Zend_Controller_Action</span>  
<span class="p">{</span>  
    <span class="k">public</span> <span class="k">function</span> <span class="nf">addAction</span><span class="p">()</span>  
    <span class="p">{</span>  
        <span class="nv">$form</span> <span class="o">=</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">getForm</span><span class="p">();</span> <span class="c1">// getting the post form  </span>
        <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">view</span><span class="o">-&gt;</span><span class="na">form</span> <span class="o">=</span> <span class="nv">$form</span><span class="p">;</span> <span class="c1">// assigning the form to view  </span>
    <span class="p">}</span>

    <span class="c1">// ... public function getForm()  </span>
<span class="p">}</span>  

<span class="o">&lt;!--</span> <span class="nx">the</span> <span class="nx">views</span><span class="o">/</span><span class="nx">scripts</span><span class="o">/</span><span class="nx">posts</span><span class="o">/</span><span class="nx">add</span><span class="o">.</span><span class="nx">phtml</span> <span class="nb">file</span> <span class="o">--&gt;</span>
<span class="o">&lt;?</span><span class="nx">php</span> <span class="k">echo</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">form</span> <span class="cp">?&gt;</span><span class="x"></span></code></pre></div>


<p>Let's create the <em>add action</em> and redirect to <em>index action</em>, our posts list, after insert. After do this, add some posts into your own application to test the results. In your browser go to something like this: <strong>http://localhost/blog&#95;app&#95;path/public/posts/add</strong>.</p>


<div class="highlight"><pre><code class="language-php" data-lang="php"><span class="o">&lt;?</span><span class="nx">php</span>

<span class="sd">/**</span>
<span class="sd"> * controllers/PostsController.php  </span>
<span class="sd"> */</span>  

<span class="k">class</span> <span class="nc">PostsController</span> <span class="k">extends</span> <span class="nx">Zend_Controller_Action</span>  
<span class="p">{</span>  
    <span class="k">public</span> <span class="k">function</span> <span class="nf">init</span><span class="p">()</span> <span class="c1">// called always before actions  </span>
    <span class="p">{</span>  
        <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">Posts</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">Posts</span><span class="p">();</span> <span class="c1">// DbTable  </span>
    <span class="p">}</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">addAction</span><span class="p">()</span>  
    <span class="p">{</span>  
        <span class="nv">$form</span> <span class="o">=</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">getForm</span><span class="p">();</span> <span class="c1">// getting the post form</span>

        <span class="k">if</span> <span class="p">(</span><span class="nv">$this</span><span class="o">-&gt;</span><span class="na">getRequest</span><span class="p">()</span><span class="o">-&gt;</span><span class="na">isPost</span><span class="p">())</span> <span class="p">{</span> <span class="c1">//is it a post request ?  </span>
            <span class="nv">$postData</span> <span class="o">=</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">getRequest</span><span class="p">()</span><span class="o">-&gt;</span><span class="na">getPost</span><span class="p">();</span> <span class="c1">// getting the $_POST data  </span>
            <span class="k">if</span> <span class="p">(</span><span class="nv">$form</span><span class="o">-&gt;</span><span class="na">isValid</span><span class="p">(</span><span class="nv">$postData</span><span class="p">))</span> <span class="p">{</span>  
                <span class="nv">$formData</span> <span class="o">=</span> <span class="nv">$form</span><span class="o">-&gt;</span><span class="na">getValues</span><span class="p">();</span> <span class="c1">// data filtered  </span>
                <span class="c1">// created and updated fields  </span>
                <span class="nv">$formData</span> <span class="o">+=</span> <span class="k">array</span><span class="p">(</span><span class="s1">&#39;created&#39;</span> <span class="o">=&gt;</span> <span class="nb">date</span><span class="p">(</span><span class="s1">&#39;Y-m-d H:i:s&#39;</span><span class="p">),</span> <span class="s1">&#39;updated&#39;</span> <span class="o">=&gt;</span> <span class="nb">date</span><span class="p">(</span><span class="s1">&#39;Y-m-d H:i:s&#39;</span><span class="p">));</span>  
                <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">Posts</span><span class="o">-&gt;</span><span class="na">insert</span><span class="p">(</span><span class="nv">$formData</span><span class="p">);</span> <span class="c1">// database insertion  </span>
            <span class="p">}</span>  
            <span class="k">else</span> <span class="nv">$form</span><span class="o">-&gt;</span><span class="na">populate</span><span class="p">(</span><span class="nv">$postData</span><span class="p">);</span> <span class="c1">// show errors and populate form with $postData  </span>
        <span class="p">}</span>

        <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">view</span><span class="o">-&gt;</span><span class="na">form</span> <span class="o">=</span> <span class="nv">$form</span><span class="p">;</span> <span class="c1">// assigning the form to view  </span>
    <span class="p">}</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">indexAction</span><span class="p">()</span>  
    <span class="p">{</span>  
        <span class="c1">// get all posts - the newer first  </span>
        <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">view</span><span class="o">-&gt;</span><span class="na">posts</span> <span class="o">=</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">Posts</span><span class="o">-&gt;</span><span class="na">fetchAll</span><span class="p">(</span><span class="k">null</span><span class="p">,</span> <span class="s1">&#39;created desc&#39;</span><span class="p">);</span>  
    <span class="p">}</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">getForm</span><span class="p">()</span>  
    <span class="p">{</span>  
        <span class="c1">// function logic  </span>
    <span class="p">}</span>  
<span class="p">}</span></code></pre></div>


<p>The <strong>posts/index.phtml</strong> file, showing the posts list.</p>


<div class="highlight"><pre><code class="language-php" data-lang="php"><span class="o">&lt;!--</span> <span class="nx">application</span><span class="o">/</span><span class="nx">views</span><span class="o">/</span><span class="nx">scripts</span><span class="o">/</span><span class="nx">posts</span><span class="o">/</span><span class="nx">index</span><span class="o">.</span><span class="nx">phtml</span> <span class="o">--&gt;</span>

<span class="o">&lt;</span><span class="nx">h1</span><span class="o">&gt;</span><span class="nx">Posts</span><span class="o">&lt;/</span><span class="nx">h1</span><span class="o">&gt;</span>

<span class="o">&lt;</span><span class="nx">table</span><span class="o">&gt;</span>
    <span class="o">&lt;</span><span class="nx">tr</span><span class="o">&gt;</span>
        <span class="o">&lt;</span><span class="nx">th</span><span class="o">&gt;</span><span class="nx">Title</span><span class="o">&lt;/</span><span class="nx">th</span><span class="o">&gt;</span>
        <span class="o">&lt;</span><span class="nx">th</span><span class="o">&gt;</span><span class="nx">Created</span><span class="o">&lt;/</span><span class="nx">th</span><span class="o">&gt;</span>
        <span class="o">&lt;</span><span class="nx">th</span><span class="o">&gt;&lt;/</span><span class="nx">th</span><span class="o">&gt;</span>
    <span class="o">&lt;/</span><span class="nx">tr</span><span class="o">&gt;</span>

    <span class="o">&lt;?</span><span class="nx">php</span> <span class="k">foreach</span> <span class="p">(</span><span class="nv">$this</span><span class="o">-&gt;</span><span class="na">posts</span> <span class="k">as</span> <span class="nv">$key</span> <span class="o">=&gt;</span> <span class="nv">$post</span><span class="p">)</span><span class="o">:</span> <span class="cp">?&gt;</span><span class="x"></span>

<span class="x">    &lt;tr&gt;</span>
<span class="x">        &lt;td&gt;</span>
<span class="x">            &lt;a href=&quot;</span><span class="cp">&lt;?php</span> <span class="k">echo</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">baseUrl</span><span class="p">(</span><span class="s1">&#39;/posts/show/id/&#39;</span> <span class="o">.</span> <span class="nv">$post</span><span class="o">-&gt;</span><span class="na">id</span><span class="p">)</span> <span class="cp">?&gt;</span><span class="x">&quot;&gt;</span>
<span class="x">                </span><span class="cp">&lt;?php</span> <span class="k">echo</span> <span class="nv">$post</span><span class="o">-&gt;</span><span class="na">title</span> <span class="cp">?&gt;</span><span class="x"></span>
<span class="x">            &lt;/a&gt;</span>
<span class="x">        &lt;/td&gt;</span>

<span class="x">        &lt;td&gt;</span>
<span class="x">            </span><span class="cp">&lt;?php</span> <span class="k">echo</span> <span class="nv">$post</span><span class="o">-&gt;</span><span class="na">created</span> <span class="cp">?&gt;</span><span class="x"></span>
<span class="x">        &lt;/td&gt;</span>

<span class="x">        &lt;td&gt;</span>
<span class="x">            &lt;a href=&quot;</span><span class="cp">&lt;?php</span> <span class="k">echo</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">baseUrl</span><span class="p">(</span><span class="s1">&#39;/posts/edit/id/&#39;</span> <span class="o">.</span> <span class="nv">$post</span><span class="o">-&gt;</span><span class="na">id</span><span class="p">)</span> <span class="cp">?&gt;</span><span class="x">&quot;&gt;Edit&lt;/a&gt;</span>
<span class="x">            &lt;a href=&quot;</span><span class="cp">&lt;?php</span> <span class="k">echo</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">baseUrl</span><span class="p">(</span><span class="s1">&#39;/posts/del/id/&#39;</span> <span class="o">.</span> <span class="nv">$post</span><span class="o">-&gt;</span><span class="na">id</span><span class="p">)</span> <span class="cp">?&gt;</span><span class="x">&quot;&gt;Delete&lt;/a&gt;</span>
<span class="x">        &lt;/td&gt;</span>
<span class="x">    &lt;/tr&gt;</span>

<span class="x">    </span><span class="cp">&lt;?php</span> <span class="k">endforeach</span> <span class="cp">?&gt;</span><span class="x"></span>

<span class="x">&lt;/table&gt;</span></code></pre></div>


<h3>Release, Update, Delete features</h3>
<p>Now let's create the actions <em>show</em>, <em>edit</em>, and <em>del</em>...</p>


<div class="highlight"><pre><code class="language-php" data-lang="php"><span class="o">&lt;?</span><span class="nx">php</span>

<span class="sd">/**</span>
<span class="sd"> * controllers/PostsController.php  </span>
<span class="sd"> */</span>  

<span class="k">class</span> <span class="nc">PostsController</span> <span class="k">extends</span> <span class="nx">Zend_Controller_Action</span>  
<span class="p">{</span>  
    <span class="c1">// init(), addAction(), indexAction() </span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">showAction</span><span class="p">()</span>  
    <span class="p">{</span>  
        <span class="nv">$id</span> <span class="o">=</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">getRequest</span><span class="p">()</span><span class="o">-&gt;</span><span class="na">getParam</span><span class="p">(</span><span class="s1">&#39;id&#39;</span><span class="p">);</span>  
        <span class="k">if</span> <span class="p">(</span><span class="nv">$id</span> <span class="o">&gt;</span> <span class="mi">0</span><span class="p">)</span> <span class="p">{</span>  
            <span class="nv">$post</span> <span class="o">=</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">Posts</span><span class="o">-&gt;</span><span class="na">find</span><span class="p">(</span><span class="nv">$id</span><span class="p">)</span><span class="o">-&gt;</span><span class="na">current</span><span class="p">();</span> <span class="c1">// or $this-&gt;Posts-&gt;fetchRow(&quot;id = $id&quot;);  </span>
            <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">view</span><span class="o">-&gt;</span><span class="na">post</span> <span class="o">=</span> <span class="nv">$post</span><span class="p">;</span>  
        <span class="p">}</span>  
        <span class="k">else</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">view</span><span class="o">-&gt;</span><span class="na">message</span> <span class="o">=</span> <span class="s1">&#39;The post ID does not exist&#39;</span><span class="p">;</span>  
    <span class="p">}</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">editAction</span><span class="p">()</span>  
    <span class="p">{</span>  
        <span class="nv">$form</span> <span class="o">=</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">getForm</span><span class="p">();</span>  
        <span class="nv">$id</span> <span class="o">=</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">getRequest</span><span class="p">()</span><span class="o">-&gt;</span><span class="na">getParam</span><span class="p">(</span><span class="s1">&#39;id&#39;</span><span class="p">);</span>

        <span class="k">if</span> <span class="p">(</span><span class="nv">$id</span> <span class="o">&gt;</span> <span class="mi">0</span><span class="p">)</span> <span class="p">{</span>  
            <span class="k">if</span> <span class="p">(</span><span class="nv">$this</span><span class="o">-&gt;</span><span class="na">getRequest</span><span class="p">()</span><span class="o">-&gt;</span><span class="na">isPost</span><span class="p">())</span> <span class="p">{</span> <span class="c1">// update form submit  </span>
                <span class="nv">$postData</span> <span class="o">=</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">getRequest</span><span class="p">()</span><span class="o">-&gt;</span><span class="na">getPost</span><span class="p">();</span>  
                <span class="k">if</span> <span class="p">(</span><span class="nv">$form</span><span class="o">-&gt;</span><span class="na">isValid</span><span class="p">(</span><span class="nv">$postData</span><span class="p">))</span> <span class="p">{</span>  
                    <span class="nv">$formData</span> <span class="o">=</span> <span class="nv">$form</span><span class="o">-&gt;</span><span class="na">getValues</span><span class="p">();</span>  
                    <span class="nv">$formData</span> <span class="o">+=</span> <span class="k">array</span><span class="p">(</span><span class="s1">&#39;updated&#39;</span> <span class="o">=&gt;</span> <span class="nb">date</span><span class="p">(</span><span class="s1">&#39;Y-m-d H:i:s&#39;</span><span class="p">));</span>  
                    <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">Posts</span><span class="o">-&gt;</span><span class="na">update</span><span class="p">(</span><span class="nv">$formData</span><span class="p">,</span> <span class="s2">&quot;id = </span><span class="si">$id</span><span class="s2">&quot;</span><span class="p">);</span> <span class="c1">// update  </span>
                    <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">_redirect</span><span class="p">(</span><span class="s1">&#39;/posts/index&#39;</span><span class="p">);</span>  
                <span class="p">}</span>  
                <span class="k">else</span> <span class="nv">$form</span><span class="o">-&gt;</span><span class="na">populate</span><span class="p">(</span><span class="nv">$postData</span><span class="p">);</span>  
            <span class="p">}</span>  
            <span class="k">else</span> <span class="p">{</span>  
                <span class="nv">$post</span> <span class="o">=</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">Posts</span><span class="o">-&gt;</span><span class="na">find</span><span class="p">(</span><span class="nv">$id</span><span class="p">)</span><span class="o">-&gt;</span><span class="na">current</span><span class="p">();</span>  
                <span class="nv">$form</span><span class="o">-&gt;</span><span class="na">populate</span><span class="p">(</span><span class="nv">$post</span><span class="o">-&gt;</span><span class="na">toArray</span><span class="p">());</span> <span class="c1">// populate method parameter has to be an array</span>

                <span class="c1">// add the id hidden field in the form  </span>
                <span class="nv">$hidden</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">Zend_Form_Element_Hidden</span><span class="p">(</span><span class="s1">&#39;id&#39;</span><span class="p">);</span>  
                <span class="nv">$hidden</span><span class="o">-&gt;</span><span class="na">setValue</span><span class="p">(</span><span class="nv">$id</span><span class="p">);</span>

                <span class="nv">$form</span><span class="o">-&gt;</span><span class="na">addElement</span><span class="p">(</span><span class="nv">$hidden</span><span class="p">);</span>  
            <span class="p">}</span>  
        <span class="p">}</span>  
        <span class="k">else</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">view</span><span class="o">-&gt;</span><span class="na">message</span> <span class="o">=</span> <span class="s1">&#39;The post ID does not exist&#39;</span><span class="p">;</span>

        <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">view</span><span class="o">-&gt;</span><span class="na">form</span> <span class="o">=</span> <span class="nv">$form</span><span class="p">;</span>  
    <span class="p">}</span>

    <span class="k">public</span> <span class="k">function</span> <span class="nf">delAction</span><span class="p">()</span>  
    <span class="p">{</span>  
        <span class="nv">$id</span> <span class="o">=</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">getRequest</span><span class="p">()</span><span class="o">-&gt;</span><span class="na">getParam</span><span class="p">(</span><span class="s1">&#39;id&#39;</span><span class="p">);</span>  
        <span class="k">if</span> <span class="p">(</span><span class="nv">$id</span> <span class="o">&gt;</span> <span class="mi">0</span><span class="p">)</span> <span class="p">{</span>  
            <span class="c1">// option 1  </span>
            <span class="cm">/*$post = $this-&gt;Posts-&gt;find($id)-&gt;current();  </span>
<span class="cm">            $post-&gt;delete();*/</span>

            <span class="c1">// option 2  </span>
            <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">Posts</span><span class="o">-&gt;</span><span class="na">delete</span><span class="p">(</span><span class="s2">&quot;id = </span><span class="si">$id</span><span class="s2">&quot;</span><span class="p">);</span>
            <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">_redirect</span><span class="p">(</span><span class="s1">&#39;/posts/index&#39;</span><span class="p">);</span>  
        <span class="p">}</span>  
    <span class="p">}</span>

    <span class="c1">// getForm()</span>

<span class="p">}</span></code></pre></div>


<p>... and the views <em>show.phtml</em> and <em>edit.phtml</em>. The <strong>delAction</strong> redirects to indexAction after insert, so it's not necessary to create a view file to it.</p>


<div class="highlight"><pre><code class="language-php" data-lang="php"><span class="c1">// application/views/scripts/posts/show.phtml</span>

<span class="o">&lt;</span><span class="nx">h1</span><span class="o">&gt;</span><span class="nx">Show</span> <span class="nx">Post</span><span class="o">&lt;/</span><span class="nx">h1</span><span class="o">&gt;</span>

<span class="o">&lt;?</span><span class="nx">php</span> <span class="k">if</span> <span class="p">(</span><span class="nv">$this</span><span class="o">-&gt;</span><span class="na">post</span><span class="p">)</span><span class="o">:</span> <span class="cp">?&gt;</span><span class="x"></span>

<span class="x">    &lt;table&gt;</span>
<span class="x">        &lt;tr&gt;</span>
<span class="x">            &lt;th&gt;ID&lt;/th&gt;</span>
<span class="x">            &lt;td&gt;</span><span class="cp">&lt;?php</span> <span class="k">echo</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">post</span><span class="o">-&gt;</span><span class="na">id</span> <span class="cp">?&gt;</span><span class="x">&lt;/td&gt;</span>

<span class="x">            &lt;th&gt;Title&lt;/th&gt;</span>
<span class="x">            &lt;td&gt;</span><span class="cp">&lt;?php</span> <span class="k">echo</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">post</span><span class="o">-&gt;</span><span class="na">title</span> <span class="cp">?&gt;</span><span class="x">&lt;/td&gt;</span>

<span class="x">            &lt;th&gt;Body&lt;/th&gt;</span>
<span class="x">            &lt;td&gt;</span><span class="cp">&lt;?php</span> <span class="k">echo</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">post</span><span class="o">-&gt;</span><span class="na">body</span> <span class="cp">?&gt;</span><span class="x">&lt;/td&gt;</span>

<span class="x">            &lt;th&gt;Post Date&lt;/th&gt;</span>
<span class="x">            &lt;td&gt;</span><span class="cp">&lt;?php</span> <span class="k">echo</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">post</span><span class="o">-&gt;</span><span class="na">created</span> <span class="cp">?&gt;</span><span class="x">&lt;/td&gt;</span>

<span class="x">            &lt;th&gt;Updated Date&lt;/th&gt;</span>
<span class="x">            &lt;td&gt;</span><span class="cp">&lt;?php</span> <span class="k">echo</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">post</span><span class="o">-&gt;</span><span class="na">updated</span> <span class="cp">?&gt;</span><span class="x">&lt;/td&gt;</span>
<span class="x">        &lt;/tr&gt;</span>
<span class="x">    &lt;/table&gt;</span>

<span class="cp">&lt;?php</span> <span class="k">else</span><span class="o">:</span> <span class="cp">?&gt;</span><span class="x"></span>

<span class="x">    </span><span class="cp">&lt;?php</span> <span class="k">echo</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">message</span> <span class="cp">?&gt;</span><span class="x"></span>

<span class="cp">&lt;?php</span> <span class="k">endif</span> <span class="cp">?&gt;</span><span class="x"></span>


<span class="x">// application/views/scripts/posts/edit.phtml</span>


<span class="x">&lt;h1&gt;Editing Post&lt;/h1&gt;</span>

<span class="cp">&lt;?php</span> <span class="k">if</span> <span class="p">(</span><span class="nv">$this</span><span class="o">-&gt;</span><span class="na">message</span><span class="p">)</span><span class="o">:</span> <span class="cp">?&gt;</span><span class="x"></span>

<span class="x">    </span><span class="cp">&lt;?php</span> <span class="k">echo</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">message</span> <span class="cp">?&gt;</span><span class="x"></span>

<span class="cp">&lt;?php</span> <span class="k">endif</span> <span class="cp">?&gt;</span><span class="x"></span>


<span class="cp">&lt;?php</span> <span class="k">echo</span> <span class="nv">$this</span><span class="o">-&gt;</span><span class="na">form</span> <span class="cp">?&gt;</span><span class="x"></span></code></pre></div>


<p>After that, test your posts CRUD and customize it according your needs.</p>
<p>Well, that's all. Use Zend Framework it's not hard and you have only understand the framework's concepts. After that, search and study some components you like in the <a href="http://framework.zend.com/manual/en/">documentation</a> and make miracles with this powerfull framework.</p>
<p>That is just an example what you can do with ZF. You can create a BaseController class and make this CRUD functionality extensible to a lot of DbTables and Controllers, using the <a href="http://en.wikipedia.org/wiki/Object-oriented_programming">OOP</a>.</p>
<p>To get this application zipped file <a href="http://juniorgrossi.com/wp-content/uploads/2011/07/basic_crud.zip">click here</a>.</p>
<p>Thanks a lot! See you...</p>
t avaiable')  
            ->addFilters(array('HtmlEntities')); // remove HTML tags

        $submit = new Zend_Form_Element_Submit('submit');  
        $submit->setLabel('Post to Blog') // the button's value  
            ->setIgnore(true); // very usefull -> it will be ignored before insertion

        $form = new Zend_Form();  
        $form->addElements(array($title, $category, $body, $submit));  
            // ->setAction('') // you can set your action. We will let blank, to send the request to the same action

        return $form; // return the form  
    }  
}

Starting to create the Add feature

Let's first show the form in view file.

<?php 

/**
 * controllers/PostsController.php  
 */  

class PostsController extends Zend_Controller_Action  
{  
    public function addAction()  
    {  
        $form = $this->getForm(); // getting the post form  
        $this->view->form = $form; // assigning the form to view  
    }

    // ... public function getForm()  
}  

<!-- the views/scripts/posts/add.phtml file -->
<?php echo $this->form ?>

Let's create the add action and redirect to index action, our posts list, after insert. After do this, add some posts into your own application to test the results. In your browser go to something like this: http://localhost/blog_app_path/public/posts/add.

<?php

/**
 * controllers/PostsController.php  
 */  

class PostsController extends Zend_Controller_Action  
{  
    public function init() // called always before actions  
    {  
        $this->Posts = new Posts(); // DbTable  
    }

    public function addAction()  
    {  
        $form = $this->getForm(); // getting the post form

        if ($this->getRequest()->isPost()) { //is it a post request ?  
            $postData = $this->getRequest()->getPost(); // getting the $_POST data  
            if ($form->isValid($postData)) {  
                $formData = $form->getValues(); // data filtered  
                // created and updated fields  
                $formData += array('created' => date('Y-m-d H:i:s'), 'updated' => date('Y-m-d H:i:s'));  
                $this->Posts->insert($formData); // database insertion  
            }  
            else $form->populate($postData); // show errors and populate form with $postData  
        }

        $this->view->form = $form; // assigning the form to view  
    }

    public function indexAction()  
    {  
        // get all posts - the newer first  
        $this->view->posts = $this->Posts->fetchAll(null, 'created desc');  
    }

    public function getForm()  
    {  
        // function logic  
    }  
}

The posts/index.phtml file, showing the posts list.

<!-- application/views/scripts/posts/index.phtml -->

<h1>Posts</h1>

<table>
    <tr>
        <th>Title</th>
        <th>Created</th>
        <th></th>
    </tr>

    <?php foreach ($this->posts as $key => $post): ?>

    <tr>
        <td>
            <a href="<?php echo $this->baseUrl('/posts/show/id/' . $post->id) ?>">
                <?php echo $post->title ?>
            </a>
        </td>

        <td>
            <?php echo $post->created ?>
        </td>

        <td>
            <a href="<?php echo $this->baseUrl('/posts/edit/id/' . $post->id) ?>">Edit</a>
            <a href="<?php echo $this->baseUrl('/posts/del/id/' . $post->id) ?>">Delete</a>
        </td>
    </tr>

    <?php endforeach ?>

</table>

Release, Update, Delete features

Now let's create the actions show, edit, and del...

<?php

/**
 * controllers/PostsController.php  
 */  

class PostsController extends Zend_Controller_Action  
{  
    // init(), addAction(), indexAction() 

    public function showAction()  
    {  
        $id = $this->getRequest()->getParam('id');  
        if ($id > 0) {  
            $post = $this->Posts->find($id)->current(); // or $this->Posts->fetchRow("id = $id");  
            $this->view->post = $post;  
        }  
        else $this->view->message = 'The post ID does not exist';  
    }

    public function editAction()  
    {  
        $form = $this->getForm();  
        $id = $this->getRequest()->getParam('id');

        if ($id > 0) {  
            if ($this->getRequest()->isPost()) { // update form submit  
                $postData = $this->getRequest()->getPost();  
                if ($form->isValid($postData)) {  
                    $formData = $form->getValues();  
                    $formData += array('updated' => date('Y-m-d H:i:s'));  
                    $this->Posts->update($formData, "id = $id"); // update  
                    $this->_redirect('/posts/index');  
                }  
                else $form->populate($postData);  
            }  
            else {  
                $post = $this->Posts->find($id)->current();  
                $form->populate($post->toArray()); // populate method parameter has to be an array

                // add the id hidden field in the form  
                $hidden = new Zend_Form_Element_Hidden('id');  
                $hidden->setValue($id);

                $form->addElement($hidden);  
            }  
        }  
        else $this->view->message = 'The post ID does not exist';

        $this->view->form = $form;  
    }

    public function delAction()  
    {  
        $id = $this->getRequest()->getParam('id');  
        if ($id > 0) {  
            // option 1  
            /*$post = $this->Posts->find($id)->current();  
            $post->delete();*/

            // option 2  
            $this->Posts->delete("id = $id");
            $this->_redirect('/posts/index');  
        }  
    }

    // getForm()

}

... and the views show.phtml and edit.phtml. The delAction redirects to indexAction after insert, so it's not necessary to create a view file to it.

// application/views/scripts/posts/show.phtml

<h1>Show Post</h1>

<?php if ($this->post): ?>

    <table>
        <tr>
            <th>ID</th>
            <td><?php echo $this->post->id ?></td>

            <th>Title</th>
            <td><?php echo $this->post->title ?></td>

            <th>Body</th>
            <td><?php echo $this->post->body ?></td>

            <th>Post Date</th>
            <td><?php echo $this->post->created ?></td>

            <th>Updated Date</th>
            <td><?php echo $this->post->updated ?></td>
        </tr>
    </table>

<?php else: ?>

    <?php echo $this->message ?>

<?php endif ?>


// application/views/scripts/posts/edit.phtml


<h1>Editing Post</h1>

<?php if ($this->message): ?>

    <?php echo $this->message ?>

<?php endif ?>


<?php echo $this->form ?>

After that, test your posts CRUD and customize it according your needs.

Well, that's all. Use Zend Framework it's not hard and you have only understand the framework's concepts. After that, search and study some components you like in the documentation and make miracles with this powerfull framework.

That is just an example what you can do with ZF. You can create a BaseController class and make this CRUD functionality extensible to a lot of DbTables and Controllers, using the OOP.

To get this application zipped file click here.

Thanks a lot! See you...