Published using Google Docs
101-Setting Up Yii Framework (XAMPP)
Updated automatically every 5 minutes

Yii: Setting Up Yii Framework

This tutorial is based on the official documentation at http://www.yiiframework.com/doc/blog/

1) WEB ENVIRONMENT SETUP

2) TESTING YII DEMO BLOG

3) CREATE NEW Yii SKELETON PROJECT

4) Yii index file - {webroot}/index.php

5) Site Controller - {webroot}/protected/controllers/SiteController.php

6) The Configuration File - {webroot}/protected/main.php

1) WEB ENVIRONMENT SETUP

1.1) Configure Virtual Host Names.

1.1.1) Open the file c:\windows\system32\drivers\etc\hosts

1.1.2) Add the following entries to the bottom of the existing codes. Restart your computer.

127.0.0.1                site1.local

127.0.0.1                site2.local

127.0.0.1                site3.local

Outcome:

1.2) Create the following folders:

C:\projects\site1

C:\projects\site2        

C:\projects\site3

1.3) Configure XAMPP httpd-vhosts file

1.3.1) Open C:\xampp\apache\conf\extra\httpd-vhosts.conf

1.3.2) Uncomment line no. 19 to enable  “NameVirtualHost *:80”

1.3.3) Add the following entries to the bottom line of the existing codes, i.e line no 44.

<VirtualHost *>

    DocumentRoot "C:/xampp/htdocs"

    ServerName localhost

</VirtualHost>

<VirtualHost *>

    DocumentRoot "C:/projects/site1"

    ServerName site1.local

         <Directory "C:/projects/site1">

                        Order allow,deny

                        Allow from all

                        Require all granted

         </Directory>        

</VirtualHost>

<VirtualHost *>

    DocumentRoot "C:/projects/site2"

    ServerName site2.local

         <Directory "C:/projects/site2">

                        Order allow,deny

                        Allow from all

                        Require all granted

         </Directory>        

</VirtualHost>

<VirtualHost *>

    DocumentRoot "C:/projects/site3"

    ServerName site3.local

         <Directory "C:/projects/site3">

                        Order allow,deny

                        Allow from all

                        Require all granted

         </Directory>        

</VirtualHost>

2) TESTING YII DEMO BLOG

The following steps require the use of 7-Zip program. The use of other unzip program may slightly differ from this program.

2.1) Open the compressed yii file and browse until you reach the following level.

Extract the folder into c:\projects\

2.2) Rename the folder as “masterframework”.

2.3) Repeat step 2.1 and extract the content of blog into c:\projects\site1\

Outcome:

2.4) Edit the file c:\projects\site1\blog\index.php as follows, i.e line no.4:

The path is supposed to point to c:\projects\masterframework\yii.php

2.5) Start the XAMPP server and browse http://site1.local/

3) CREATE NEW Yii SKELETON PROJECT

Yii framework comes with a command line program yiic that generates skeleton files for yii project.

3.1) To use this, you need to register the PHP and Yii path as the environment variables.

The following screenshot shows the path “C:\xampp\php;c:\projects\masterframework\” is added to the Path variable.

3.2) Test that you have successfully registered the correct path by issuing commands:

php –v

yiic

3.3) You are now ready to run yiic. Go to C:\projects and run “yiic webapp ./site2”

3.4) Yiic will generate the skeleton files under the folder site2. Wait for the process to complete.

3.5) Test that you have successfully created the project by browsing http://site2.local

4) Yii index file - {webroot}/index.php

4.1) Open Yii index.php using notepad++. Notice the following lines:

..4. Path to Yii Bootstrap File.

..5. Path to Application’s Configuration File

..8. Set YII_DEBUG to true (for development; to display debug message)

..10. Set the Trace Level

..13. Creates an application instance with the specified configuration and executes the application. (Calling the method createWebApplication() of the class Yii to create a Web Application Object and call the run() method to run the object.)

  1. <?php
  2. // change the following paths if necessary
  3. $yii=dirname(__FILE__).'/../masterframework/yii.php';
  4. $config=dirname(__FILE__).'/protected/config/main.php';
  5. // remove the following lines when in production mode
  6. defined('YII_DEBUG') or define('YII_DEBUG',true);
  7. // specify how many levels of call stack should be shown in each log message
  8. defined('YII_TRACE_LEVEL') or define('YII_TRACE_LEVEL',3);
  9. require_once($yii);
  10. Yii::createWebApplication($config)->run();

The content of “protected” folder is protected from web users through the use of .htaccess file located within that folder.

The content of .htaccess says “deny from all” which means deny access from all users.

5) Site Controller - {webroot}/protected/controllers/SiteController.php

5.1) 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

5.2) 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.3) Refers to the file SiteController.php above

Notice that it has action methods:

5.4) You can call these action methods through URL call, e.g when you type http://site2.local/index.php?r=site/contact, the method actionContact will be invoked.

actionContact will create a form object, $model and passes the object to SiteController for render.

6) The Configuration File - {webroot}/protected/main.php

Main.php contains the application configuration such as:

<?php

// uncomment the following to define a path alias

// Yii::setPathOfAlias('local','path/to/local-folder');

// This is the main Web application configuration. Any writable

// CWebApplication properties can be configured here.

return array(

        'basePath'=>dirname(__FILE__).DIRECTORY_SEPARATOR.'..',

        'name'=>'My Web Application',

        // preloading 'log' component

        'preload'=>array('log'),

        // autoloading model and component classes

        'import'=>array(

                'application.models.*',

                'application.components.*',

        ),

        'modules'=>array(

                // uncomment the following to enable the Gii tool

                /*

                'gii'=>array(

                        'class'=>'system.gii.GiiModule',

                        'password'=>'Enter Your Password Here',

                        // If removed, Gii defaults to localhost only. Edit carefully to taste.

                        'ipFilters'=>array('127.0.0.1','::1'),

                ),

                */

        ),

        // application components

        'components'=>array(

                'user'=>array(

                        // enable cookie-based authentication

                        'allowAutoLogin'=>true,

                ),

                // uncomment the following to enable URLs in path-format

                /*

                'urlManager'=>array(

                        'urlFormat'=>'path',

                        'rules'=>array(

                                '<controller:\w+>/<id:\d+>'=>'<controller>/view',

                                '<controller:\w+>/<action:\w+>/<id:\d+>'=>'<controller>/<action>',

                                '<controller:\w+>/<action:\w+>'=>'<controller>/<action>',

                        ),

                ),

                */

                'db'=>array(

                        'connectionString' => 'sqlite:'.dirname(__FILE__).'/../data/testdrive.db',

                ),

                // uncomment the following to use a MySQL database

                /*

                'db'=>array(

                        'connectionString' => 'mysql:host=localhost;dbname=testdrive',

                        'emulatePrepare' => true,

                        'username' => 'root',

                        'password' => '',

                        'charset' => 'utf8',

                ),

                */

                'errorHandler'=>array(

                        // use 'site/error' action to display errors

                        'errorAction'=>'site/error',

                ),

                'log'=>array(

                        'class'=>'CLogRouter',

                        'routes'=>array(

                                array(

                                        'class'=>'CFileLogRoute',

                                        'levels'=>'error, warning',

                                ),

                                // uncomment the following to show log messages on web pages

                                /*

                                array(

                                        'class'=>'CWebLogRoute',

                                ),

                                */

                        ),

                ),

        ),

        // application-level parameters that can be accessed

        // using Yii::app()->params['paramName']

        'params'=>array(

                // this is used in contact page

                'adminEmail'=>'webmaster@example.com',

        ),

);