Tuesday, November 26, 2013

Yii Quick Start 3 (Adding Theme) (UsbWebserver)

Yii Quick Start 3 (Adding Theme)
  • Introduction
  • Steps
  • Conclusion


Introduction

This tutorial explains the role of the layout and theme in Yii website.

Steps

1) Using File explorer, browse {webroot}/protected/views/layouts/…
By default, there are three layout files; main.php, column1.php and column2.php
Layout files specify the arrangement of HTML elements of a Yii web page.
2) The display of HTML elements is further defined by the theme.
Using File Explorer, browse {webroot}/themes/…
The default theme is classic. It doesn’t contain anything actually.
3) We can add new themes by simply adding a theme folder into the themes folder and edit the configuration file.
3.2) Extract the folder “mattskitchen” into the themes folder.
Make sure the folder structures follow the example below.
3.3) Edit the configuration file {webroot}/protected/config/main.php
Add the line ‘theme’=>’mattskitchen’,
4) Refresh your browser.
You should be getting a new look.
However, the HOME link doesn’t work.
5) This is because the index controller specified in the hyperlink could not be found.
If you open the file {webroot}/protected/controllers/SiteController.php, you won’t find the name actionIndex.
Instead actionIndex is defined in {webroot}/protected/controllers/PostController.php.
6) Edit the file {webroot}/themes/mattskitchen/views/layouts/main.php
Replace the word “site” with “post” (as shown in the example below).
7) Refresh your browser.
The index page problem is solved but the sidebar doesn’t show up.
It could be that the column2.php in mattskitchen is missing or not according to the initial column2.php
8) As a solution, copy the file {webroot}/protected/views/layouts/column2.php to the {webroot}/themes/mattskitchen/views/layouts/…
9) Refresh your browser. You may get the desired outcome now.
10) There are a lot of free themes available at http://yii.themefactory.net/theme that you can try out.

Conclusion

This tutorial explains the role of the Layout and Theme to define the arrangement and look of a Yii web page. You need to know the location of action methods and pages in order to call them properly. In addition to that, your knowledge in HTML and CSS elements would be beneficial to help you troubleshooting page layout or display problem.

Yii Quick Start 2 (BootStrap, OOP, MVC and REST) (UsbWebserver)

Yii Quick Start 2


  • Introduction
  • Steps
  • Conclusion


Introduction

This tutorial explains the role of the index.php of a Yii website as a bootstrap. Bootstrap means to load a small program that eventually calls the desired program into the computer, similar to an operating system being called by a BIOS program.

Steps

1) Using File Explorer browse the Yii Blog Demo root file.
2) The name index.php is a common name found in PHP websites.
The content of the file is as follows:
Line no. 4 tells the server the location of Yii Framework folder.
Line no. 5 tells the server the location of the configuration details for this website.
Line no. 6 tells the server to include the yii.php when processing the index.php
Line no. 11 tells the server to create a static Web Application object based on the given configuration (in Line no. 5). This is an Object Oriented style of programming.
3) By default, Yii Web Application Object passes the control to {webroot}/protected/controllers/SiteController.php
How does it happen? Look at the following tracing table.
File Name
Line No.Code
Extract
Index.php
13
Yii::createWebApplication($config)->run();
Yii.php
25
class Yii extends YiiBase
YiiBase.php
98
return self::createApplication('CWebApplication',$config);
CWebApplication.php
63
public $defaultController='site';
The word ‘site’ refers to {webroot}/protected/controllers/SiteController.php
4) Open {webroot}/protected/controllers/SiteController.php
The instruction “$this->render('index');” will render the view file ‘protected/views/site/index.php’ using the default layout ‘protected/views/layouts/main.php’
View File = File that feeds the content to $content element.
Layout File = File that contains the elements HTML Header, Main Menu, BreadCrumb, $content and Footer.
<?php
class SiteController extends Controller
{
        /**
         * Declares class-based actions.
         */
        public function actions()
        {
                return array(
                        // captcha action renders the CAPTCHA image displayed on the contact page
                        'captcha'=>array(
                                'class'=>'CCaptchaAction',
                                'backColor'=>0xFFFFFF,
                        ),
                        // page action renders "static" pages stored under 'protected/views/site/pages'
                        // They can be accessed via: index.php?r=site/page&view=FileName
                        'page'=>array(
                                'class'=>'CViewAction',
                        ),
                );
        }
        /**
         * This is the default 'index' action that is invoked
         * when an action is not explicitly requested by users.
         */
        public function actionIndex()
        {
                // renders the view file 'protected/views/site/index.php'
                // using the default layout 'protected/views/layouts/main.php'
                $this->render('index');
        }
        /**
         * This is the action to handle external exceptions.
         */
        public function actionError()
        {
        ...
        }
        /**
         * Displays the contact page
         */
        public function actionContact()
        {
         ...
        }
        /**
         * Displays the login page
         */
        public function actionLogin()
        {
        ...
        }
        /**
         * Logs out the current user and redirect to homepage.
         */
        public function actionLogout()
        {
        ...
        }
}
5) Refers to the file SiteController.php above
Notice that it has action methods:
  • actionIndex
  • actionError
  • actionContact
  • actionLogin
  • actionLogout
6) You can call these action methods through URL call, e.g when you type http://localhost:8080/yii/demos/blog/index.php/site/contact, the method actionContact will be invoked. The method actionContact will create a form object, $model and passes the object to SiteController for render. This is also known as RESTful style (read more here, http://rest.elkstein.org/)

Conclusion


This tutorial shows how Yii uses Object Oriented Programming to implement the Model-View-Control framework.

Yii Quick Start 1 (Download Startup files) (UsbWebserver)

Yii Quick Start 1

  • Introduction
  • Setting up the Apache-MySQL-PHP server and Yii Framework
  • Conclusion

Introduction

This tutorial attempts to provide the quickest way for a person to start understanding and using Yii Framework. No prerequisite knowledge is necessary. You just need to have a Windows PC in order to follow the steps below.

Setting up the Apache-MySQL-PHP server and Yii Framework

1) Download the starter file from here, https://drive.google.com/file/d/0B86b-ALn-1MGLVlZLXQ0Vk9UWnc/edit?usp=sharing . It’s a prepackaged files containing usbwebserver Apache-MySQL-PHP bundle, Yii framework, Yii demos and Yii webapp site.

2) The filename that you download is USBWY.zip. If you unzipped it, it may have the following structure.
It is recommended that you extract the file contents close to your computer root, e.g. C:\Z\USBWY...

3) Notice the file name usbwebserver.exe and the folder name “root”.
4) Run usbwebserver.exe.
If you get a non-english words like the above, click the button “Instellingen” and change the language to English. Click “Opslaan” to Save your option.
5) In the General panel of the USBWebServer Control Window, notice the button “Root dir” and “Localhost”.
6) If you click “Root dir”, you would get the File Explorer application browsing the root folder (refer Step 2)
7) Go into the root folder.
Notice the file index.php
8) Refer to Step 5, click on the button “Localhost”.
This is the web page rendered by the file index.php in Step 7.
9) Add “/yii” to the URL above.
The content of yii folder is displayed.
However, if you browse the file using File Explorer, you may notice that one folder is missing in the above list.
10) Go into the folder “framework”.
Notice that there is a file “.htaccess”.
The file contains the command “deny from all”.
That’s why the folder is not visible.
Even if you add the folder name to the URL, you will get page error.
11) The Steps 9 and 10 demonstrates the function of .htaccess in Apache server that controls the web access to files and folders on a website.
It doesn’t belong to Yii Framework but it helps to protect the Yii Framework files from unauthorized access and use.

You should get the Yii Blog Demo. This demo websites shows you the example of Yii Framework application.

Conclusion

This is a simple preconfigured setup for Yii Framework aimed at helping a beginner to quickly understand and use the framework. It may not be the best setting for production server. As you follow through this tutorial series, you may learn a better way of setting up Yii Framework for production server.

Thursday, November 14, 2013

Yii: Creating Demo Blog 3 (XAMPP)


---
Yii: Creating Demo Blog 3
Comments Management -
======================================================================================
======================================================================================

A) CUSTOMIZING COMMENT MODEL

1) Customizing rules() Method

1.1) Modify {webroot}/protected/models/Comment.php
Edit rules()
Public function rules()
{
    return array(
        array('content, author, email', 'required'),
        array('author, email, url', 'length', 'max'=>128),
        array('email','email'),
        array('url','url'),
    );
}

2) Customizing AttributeLabels() Method

Modify {webroot}/protected/models/Comment.php
Edit
public function attributeLabels()
{
    return array(
        'id' => 'Id',
        'content' => 'Comment',
        'status' => 'Status',
        'create_time' => 'Create Time',
        'author' => 'Name',
        'email' => 'Email',
        'url' => 'Website',
        'post_id' => 'Post',
    );
}

3) Customizing Saving Process

Modify {webroot}/protected/models/Comment.php
Add
protected function beforeSave()
{
    if(parent::beforeSave())
    {
        if($this->isNewRecord)
            $this->create_time=time();
        return true;
    }
    else
        return false;
}

4) Add additional methods for Comment

Modify {webroot}/protected/models/Comment.php
getURL()
getAuthorLink()
getPendingCommentCount()
findRecentComments()
        /**
         * @param Post the post that this comment belongs to. If null, the method
         * will query for the post.
         * @return string the permalink URL for this comment
         */
        public function getUrl($post=null)
        {
                if($post===null)
                        $post=$this->post;
                return $post->url.'#c'.$this->id;
        }
        /**
         * @return string the hyperlink display for the current comment's author
         */
        public function getAuthorLink()
        {
                if(!empty($this->url))
                        return CHtml::link(CHtml::encode($this->author),$this->url);
                else
                        return CHtml::encode($this->author);
        }
        /**
         * @return integer the number of comments that are pending approval
         */
        public function getPendingCommentCount()
        {
                return $this->count('status='.self::STATUS_PENDING);
        }
        /**
         * @param integer the maximum number of comments that should be returned
         * @return array the most recently added comments
         */
        public function findRecentComments($limit=10)
        {
                return $this->with('post')->findAll(array(
                        'condition'=>'t.status='.self::STATUS_APPROVED,
                        'order'=>'t.create_time DESC',
                        'limit'=>$limit,
                ));
        }

5) Add additional file into {webroot}/protected/views/post/ folder

filename: _comments.php
<?php foreach($comments as $comment): ?>
<div class="comment" id="c<?php echo $comment->id; ?>">


<?php echo CHtml::link("#{$comment->id}", $comment->getUrl($post), array(
'class'=>'cid',
'title'=>'Permalink to this comment',
)); ?>


<div class="author">
<?php echo $comment->authorLink; ?> says:
</div>


<div class="time">
<?php echo date('F j, Y \a\t h:i a',$comment->create_time); ?>
</div>


<div class="content">
<?php echo nl2br(CHtml::encode($comment->content)); ?>
</div>


</div><!-- comment -->
<?php endforeach; ?>


B) CREATING AND DISPLAYING COMMENTS

1) Displaying Comments.
1.1) Modify {webroot}/protected/views/post/view.php
<?php
$this->breadcrumbs=array(
        $model->title,
);
$this->pageTitle=$model->title;
?>
<?php $this->renderPartial('_view', array(
        'data'=>$model,
)); ?>
<div id="comments">
        <?php if($model->commentCount>=1): ?>
                <h3>
                        <?php echo $model->commentCount>1 ? $model->commentCount . ' comments' : 'One comment'; ?>
                </h3>
                <?php $this->renderPartial('_comments',array(
                        'post'=>$model,
                        'comments'=>$model->comments,
                )); ?>
        <?php endif; ?>
        <h3>Leave a Comment</h3>
        <?php if(Yii::app()->user->hasFlash('commentSubmitted')): ?>
                <div class="flash-success">
                        <?php echo Yii::app()->user->getFlash('commentSubmitted'); ?>
                </div>
        <?php else: ?>
                <?php $this->renderPartial('/comment/_form',array(
                        'model'=>$comment,
                )); ?>
        <?php endif; ?>
</div><!-- comments -->
1.2) Modify {webroot}/protected/controllers/PostController.php
Edit actionView().
public function actionView()
{
    $post=$this->loadModel();
    $comment=$this->newComment($post);

    $this->render('view',array(
        'model'=>$post,
        'comment'=>$comment,
    ));
}
Add newComment()
protected function newComment($post)
{
    $comment=new Comment;

    if(isset($_POST['ajax']) && $_POST['ajax']==='comment-form')
    {
        echo CActiveForm::validate($comment);
        Yii::app()->end();
    }

    if(isset($_POST['Comment']))
    {
        $comment->attributes=$_POST['Comment'];
        if($post->addComment($comment))
        {
            if($comment->status==Comment::STATUS_PENDING)
                Yii::app()->user->setFlash('commentSubmitted','Thank you for your comment. Your comment will be posted once it is approved.');
            $this->refresh();
        }
    }
    return $comment;
}
1.3) Modify {webroot}/protected/model/Post.php
public function addComment($comment)
{
    if(Yii::app()->params['commentNeedApproval'])
        $comment->status=Comment::STATUS_PENDING;
    else
        $comment->status=Comment::STATUS_APPROVED;
    $comment->post_id=$this->id;
    return $comment->save();
}
1.4) Modify {webroot}/protected/views/comment/_form.php
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
        'id'=>'comment-form',
        'enableAjaxValidation'=>true,
)); ?>
        <p class="note">Fields with <span class="required">*</span> are required.</p>
        <div class="row">
                <?php echo $form->labelEx($model,'author'); ?>
                <?php echo $form->textField($model,'author',array('size'=>60,'maxlength'=>128)); ?>
                <?php echo $form->error($model,'author'); ?>
        </div>
        <div class="row">
                <?php echo $form->labelEx($model,'email'); ?>
                <?php echo $form->textField($model,'email',array('size'=>60,'maxlength'=>128)); ?>
                <?php echo $form->error($model,'email'); ?>
        </div>
        <div class="row">
                <?php echo $form->labelEx($model,'url'); ?>
                <?php echo $form->textField($model,'url',array('size'=>60,'maxlength'=>128)); ?>
                <?php echo $form->error($model,'url'); ?>
        </div>
        <div class="row">
                <?php echo $form->labelEx($model,'content'); ?>
                <?php echo $form->textArea($model,'content',array('rows'=>6, 'cols'=>50)); ?>
                <?php echo $form->error($model,'content'); ?>
        </div>
        <div class="row buttons">
                <?php echo CHtml::submitButton($model->isNewRecord ? 'Submit' : 'Save'); ?>
        </div>
<?php $this->endWidget(); ?>
</div><!-- form -->

C) MANAGING COMMENTS

1) Approving Comments
public function actionApprove()
{
    if(Yii::app()->request->isPostRequest)
    {
        $comment=$this->loadModel();
        $comment->approve();
        $this->redirect(array('index'));
    }
    else
        throw new CHttpException(400,'Invalid request...');
}
{webroot}/protected/models/Comment.php
        public function approve()
        {
                $this->status=Comment::STATUS_APPROVED;
                $this->update(array('status'));
        }
public function actionIndex()
{
    $dataProvider=new CActiveDataProvider('Comment', array(
        'criteria'=>array(
            'with'=>'post',
            'order'=>'t.status, t.create_time DESC',
        ),
    ));

    $this->render('index',array(
        'dataProvider'=>$dataProvider,
    ));
}




2) Modify {webroot}/protected/controllers/CommentController.php

Edit AccessRule Line.no 40
Replace 'admin' with @.


Labels