CakePHP Blog Tutorial


Basic Information

CakePHP version: 2.5.4
Platform: XAMPP, Windows

Preparation

  1. Step 1:
    Download the initial code using this link and put it in C:/xampp/htdocs
  2. Step 2:
    Command prompt to C:\xampp\mysql\bin
  3. Step 3:
    Run "mysql.exe -u root" to login mysql (xampp mysql default password is empty for account 'root')
  4. Step 4:
    Run "CREATE DATABASE TESTDB;"
  5. Step 5: 
    Run "USE TESTDB;"
  6. Step 6:
    Create the tables needed and insert some sample data.
    CREATE TABLE IF NOT EXISTS posts (
         id int(11) NOT NULL auto_increment,
         title varchar(50) default NULL,
         content text,
         created datetime default NULL,
         modified datetime default NULL,
         published tinyint(1) NOT NULL default 1,
         PRIMARY KEY (id)
    );
    
    INSERT INTO posts
    (id, title, content, created, modified, published) VALUES
    (1, 'Another day Still Looking', 'My Lion ran off', '2008-06-19 18:26:11', '2008-06-19 18:26:11', 1);
    
    INSERT INTO posts
    (id, title, content, created, modified, published) VALUES
    (2, 'A good day', 'The lion is back in one piece', '2008-06-19 18:31:50', '2008-06-19 18:31:50', 1),
    (3, 'Thank GOD', 'Everything belongs to my father', '2008-06-20 18:42:50', '2008-06-19 18:42:50', 1);

Get to work

  1. Step 1:
    Create model post.php (app/model/post.php)
    <?php
    class Post extends AppModel{
     var $name = 'Post';
     // In the validate array, 
     // each element's key corresponds to the name of 
     // the input element to be validated (for example, title),
     // and its value defines the rules to apply against the input 
     // before the post data is saved to the 'posts' table -- when the post form is submitted
     var $validate = array( 'title'=>array(
        'alphaNumeric' => array(
         'rule' => 'alphaNumeric',
         'required' => true,
         'message' => 'Enter a titlefor this post',
           )
          ),
        'content' => array(
        'alphaNumeric'=>array(
         'rule'=>'alphaNumeric',
         'reuqired'=>true,
         'message'=>'Enter some content for your post'
           )
          )
         );
    }
    ?>
    

  2. Step 2: 
    Create controller PostController.php (app/controller/PostController.php)

    1. <?php
      class PostController extends AppController{
       var $name = 'Posts';
       
       // First, we add the index method, which displays the list of posts.
       // By default, this method is called explicitly during a URL request
       // along with showing all the published posts, the index page contains 
       // links that will enable users to perform operations such as 
       // edit, publish, unpublished and delete a post record.
       function index() {
        // uses the Post model object with its default 'find' method to 
        // pull all the posts from the 'posts' database table
        // and then store the results in  an array called $posts
        $posts = $this->Post->find('all');
        // The second prepares and sets the $posts records so that 
        // the views/posts/index.ctp file can display the list of all the posts
        // from the $posts variable
        $this->set(compact('posts'));
       }
      }
      ?>
  3. Step 3:
    Create folder 'Post' in app/View/
  4. Step 4:
    Create index.ctp inside app/View/Posts/ and add the following code:

    
    <div id="center_content">
     <h2>Post Listings</h2>
     <p>Here is a list of the existing posts.</p>
     <div></div>
     <?php
      if (isset($posts) && is_array($posts)){
     ?>
      <table>
       <tr>
        <td>
         <b>ID></b>
        </td>
        <td>
         <b>content</b>
        </td>
        <td>
         <b>Last Modified</b>
        </td>
        <td>
         <b>published</b>
        </td>
        <td colspan="2">
         <b>&nbsp;&nbsp;Action</b>
        </td>
       </tr>
       <?php foreach ($posts as $post): ?>
        <tr>
         <td><?php echo $post['Post']['id']; ?></td>
         <td><?php echo $post['Post']['title']; ?></td>
         <td><?php echo $post['Post']['content']; ?></td>
         <td><?php echo $post['Post']['modified']; ?></td>
         <td>
         <?php if($post[ 'Post' ][ 'published' ] == 1) { 
           echo $this->Html->link('Publish', array('action'=>'disable', $post[ 'Post' ][ 'id' ]));
          }else{
           echo $this->Html->link('Unpublish', array('action'=>'enable', $post[ 'Post' ][ 'id' ]));
          }
          ?>
         </td>
         <td>
          <?php 
           echo $this->Html->link('Edit', array('action'=>'edit', $post[ 'Post' ][ 'id' ]), null);
          ?>
         </td>
         <td>
          <?php echo $this->Html->link(__('Delete', true), array('action'=>'delete', $post[ 'Post' ][ 'id' ]), null, sprintf(__('Are you sure you want to delete Post # %s?', true), $post[ 'Post' ][ 'id' ]));?>
         </td>
        </tr>
       <?php endforeach;?>
       <?php
        if (sizeof($posts)==0){
       ?>
        <tr style="background-color: #cccccc;">
         <td colspan="6">
          <span style="font-size:17px;">
           No post found.
         </td>
        </tr>
       <?php
        }
       ?>
      </table>
      <br/>
     <?php
      }
     ?>
    </div>
    

  5. Step 5: Create index.ctp inside app/View/Posts/ and add the following code:
    <div id="center_content">
     <h2>Post Listings</h2>
     <p>Here is a list of the existing posts.</p>
     <div></div>
     <?php
      if (isset($posts) && is_array($posts)){
     ?>
      <table>
       <tr>
        <td>
         <b>ID></b>
        </td>
        <td>
         <b>content</b>
        </td>
        <td>
         <b>Last Modified</b>
        </td>
        <td>
         <b>published</b>
        </td>
        <td colspan="2">
         <b>&nbsp;&nbsp;Action</b>
        </td>
       </tr>
       <?php foreach ($posts as $post): ?>
        <tr>
         <td><?php echo $post['Post']['id']; ?></td>
         <td><?php echo $post['Post']['title']; ?></td>
         <td><?php echo $post['Post']['content']; ?></td>
         <td><?php echo $post['Post']['modified']; ?></td>
         <td>
         <?php if($post[ 'Post' ][ 'published' ] == 1) { 
           echo $this->Html->link('Publish', array('action'=>'disable', $post[ 'Post' ][ 'id' ]));
          }else{
           echo $this->Html->link('Unpublish', array('action'=>'enable', $post[ 'Post' ][ 'id' ]));
          }
          ?>
         </td>
         <td>
          <?php 
           echo $this->Html->link('Edit', array('action'=>'edit', $post[ 'Post' ][ 'id' ]), null);
          ?>
         </td>
         <td>
          <?php echo $this->Html->link(__('Delete', true), array('action'=>'delete', $post[ 'Post' ][ 'id' ]), null, sprintf(__('Are you sure you want to delete Post # %s?', true), $post[ 'Post' ][ 'id' ]));?>
         </td>
        </tr>
       <?php endforeach;?>
       <?php
        if (sizeof($posts)==0){
       ?>
        <tr style="background-color: #cccccc;">
         <td colspan="6">
          <span style="font-size:17px;">
           No post found.
         </td>
        </tr>
       <?php
        }
       ?>
      </table>
      <br/>
     <?php
      }
     ?>
    </div>
    
  6. Step 6: Check out the result in http://localhost/kevlog/post/index

Create a post

  1. Step 1:
    Add the 'add' method in PostController.

    function add() {
      // Heading and slogan for the add view page
      // This is necesaary because we are going to use 
      // a single element view to displaythe forms to add and edit posts
      // elements in Cake enables you to reuse views
      $actionHeading = 'Add a Post!';
      $actionSLogan = 'Please fill in all fields. Feel free to add your post and express your opinion.';
    
      $this->set(compact('actionHeading','actionSlogan'));
    
      // Next, we check if the add post form has been submitted.
      // If the form has not been submitted, the add view is displayed.
      // If the submitted data ($this->data) is not empty, 
      // using the 'save' method of the Post model object,
      // the application will attempt to create a new post record.
      // The 'save' method automatically uses the validation rules defined
      // in the Post Model to check the integrity of the sunmitted text.
      // If the post does not pass the validation rules,
      // the error message is set, using the 'setFlash' method of the 'Session' object.
      // Otherwise, the post is saved to the database table,
      // and the success message is set for display in the view.
      if (!empty($this->data)){
       $this->Post->create();
       if ($this->Post->save($this->data)){
        $this->Session->setFlash(_('The Post has been saved',true));
        $this->redirect(array('action'=>'index'));
       } else {
        $this->Session->setFlash(_('The Post could not be saved. Please try again.', true));
       }
      }
     }
    


  2. Step 2: 
    Create the add view and store the codes in app/view/posts/add.ctp file

    <?php
     // The $this->element accepts the name of a file stored 
     // in the view/elements folder (add_or_edit in this case),
     // without the file extension (without .ctp).
     // It simply transfers the content of add_or_edit.ctp into the add.ctp.
     echo $this->element('add_or_edit');
    ?>
    
  3. Step 3:
    Create the add_or_edit.ctp file in app/view/elements/
    <fieldset>
        <legend>
            <?php
                __('Add a Post!');
            ?>
        </legend>
        Please fill in all fields.
        <?php
            echo $this->Form->create('Post');
            echo $this->Form->error('Post.title');
            echo $this->Form->input('Post.title',
                                array('id'=>'postitle',
                                        'label'=>'Title:',
                                        'size'=> 50,
                                        'maxlength'=>255,
                                        'error'=>false));
            echo $this->Form->error('Post.content');
            echo $this->Form->input('Post.content',
                                array('id'=>'postcontent',
                                        'type'=>'textarea',
                                        'label'=>'Content',
                                        'rows'=>10,
                                        'error'=>false));
            echo $this->Form->end(array('label'=>'Submit Post'));
        ?>
    </fieldset>
    

  4. Step 4:
    Create the add_or_edit.ctp file in app/view/elements/

    <fieldset>
        <legend>
            <?php
                __('Add a Post!');
            ?>
        </legend>
        Please fill in all fields.
        <?php
            echo $this->Form->create('Post');
            echo $this->Form->error('Post.title');
            echo $this->Form->input('Post.title',
                                array('id'=>'postitle',
                                        'label'=>'Title:',
                                        'size'=> 50,
                                        'maxlength'=>255,
                                        'error'=>false));
            echo $this->Form->error('Post.content');
            echo $this->Form->input('Post.content',
                                array('id'=>'postcontent',
                                        'type'=>'textarea',
                                        'label'=>'Content',
                                        'rows'=>10,
                                        'error'=>false));
            echo $this->Form->end(array('label'=>'Submit Post'));
        ?>
    </fieldset>
    

  5. Step 5:
    Check out the result in http://localhost/kevlog/post/add
  6. Step 6:
    For all the code edited, you can refer this git diff: link
  7. Step 7:
    For more explanation of add_or_edit.ctp, you can refer to this git diff: link

Edit a post

  1. Step 1:
    Add the 'edit' method in PostController

    function edit($id=null) {
     $actionHeading = 'Edit a Post!';
     $actionSlogan = 'Please fill in all fields. Now you can amend your post.';
    
     $this->set(compact('actionHeading','actionSlogan'));
    
     // Check whether $id and $this->data are empty,
     // or an error message will be stored in our 'Session' object,
     // and the request is redirected to the blog home page.
     if (!$id && empty($this->data)) {
      $this->Session->setFlash(_('Invalid Post',true));
      $this->redirect(array('action'=>'index'));
     }
    
     // If the submitted formdata is not empty,
     // Cake will try to commit the edited post information to the posts database table
     // and then flash appropriate messages upon success or failure. 
     // Finally, if only the submitted data is empty, a post's information is pulled
     // with the 'Post' model 'read' method using the supplied $id as the criterion.
     if (!empty($this->data)) {
      if ($this->Post->save($this->data)) {
       $this->Session->setFlash(_('The Post has been saved', true));
       $this->redirect(array('action'=>'index'));
      } else {
       $this->Session->setFlash(_('The Post could not be saved. Please try again.', true));
      }
     }
    
     if (empty($this->data)){
      $this->data = $this->Post->read(null,$id);
     }
    }
    

  2. Step 2:
    Create the edit view and store the codes in app/view/posts/edit.ctp file

    <?php
     echo $this->element('add_or_edit');
    ?>
    
  3. Step 3:
    Check out the result in http://localhost/kevlog/post/edit/1
  4. Step 4:
    For all the code edited, you can reer to this git diff: link

Unpublishing a post

  1. Step 1:
    Add the ‘disable’ method in PostController

    function disable($id=null){
     // A post record is retrieved from the 'posts' database table
     // and stored inthe $post variable.
     $post = $this->Post->read(null,$id);
     if (!id && empty($post)) {
      $this->Session->setFlash(__('You must provide a valid ID number to disable a post', true));
      $this->redirect(array('action'=>'index'));
     }
    
     if (!empty($post)) {
      // If there is a valid $id and the $post is not empty, 
      // we set the post published elemet to 0 and 
      // update the 'posts' database table. 
      // Finally, the 'Session' object sets the appropriate message,
      // and then we redirect to the blog home page.
      $post['Post']['published'] = 0;
      if ($this->Post->save($post)){
       $this->Session->setFlash(__('Post ID '.$id.' has been disabled.',true));
      } else {
       $this->Session->setFlash(__('Post ID'.$id.' was not saved.',true));
      }
      $this->redirect(array('action'=>'index'));
     } else {
      // If the $id value is null or the $post variable is empty,
      // we use the 'Session' object to set the appropriate message
      // and redirect to the blog home page
      $this->Session->setFlash(__('No Post by that ID was found.', true));
      $this->redirect(array('action'=>'index'));
     }
    }
    
  2. Step 2:
    For all the code edited, you can refer to this git diff: link

Publishing a post

  1. Add the 'enable' method in PostController

    function enable($id=null){
     $post=$this->Post->read(null,$id);
     if (!id && empty($post)) {
      $this->Session->setFlash(__('You must provide a valid ID number to disable a post', true));
      $this->redirect(array('action'=>'index'));
     }
    
     if (!empty($post)) {
      $post['Post']['published'] = 1;
      if ($this->Post->save($post)){
       $this->Session->setFlash(__('Post ID '.$id.' has been enabled.',true));
      } else {
       $this->Session->setFlash(__('Post ID'.$id.' was not saved.',true));
      }
      $this->redirect(array('action'=>'index'));
     } else {
      $this->Session->setFlash(__('No Post by that ID was found.', true));
      $this->redirect(array('action'=>'index'));
     }
    }
    
  2. Step 2:
    For all the code edited, you can refer to this git diff: link

Deleting a post

  1. Step 1:
    Add the 'delete' method in PostController
  2. function delete($id=null){
     if (!$id){
      $this->Session->setFlash(__('Invalid id for Post',true));
      $this->redirect(array('action'=>'index'));
     }
     if ($this->Post->delete($id)){
      $this->Session->setFlash(__('Post deleted', true));
      $this->redirect(array('action'=>'index'));
     }
    }
  3. Step 2:For all the code edited, you can refer to this git diff: link
CakePHP Blog Tutorial CakePHP Blog Tutorial Reviewed by Kevin Lai on 9:52:00 AM Rating: 5

No comments:

Powered by Blogger.