Pages

Tuesday, December 10, 2013

Test your Database Connection

After setting up the your MySQL connection in your web application (see my previous post), you should ensure that your database connection is actually working especially for new server setups. Let me introduce you to the interactive shell for your application and ensure that there are no errors when you attempt to reference the application db component.

Using the interactive shell

As you would remember, we used the command line utility called yiic to create a new web application in Yii. Another command you can use with yiic is called shell. This will allow you to run PHP commands within the context of the Yii application, straight from the command line.

To start the shell, go to the root directory of your application, that is the directory where you can located index.php entry script. Then run the yiic utility and passing in shell as the command. See the screenshot below





This will allow you to enter the commands directly after the >> prompt.

You would want to test your db connection to ensure that your MySQL Database is accessible from your web application. You can simply echo out the connection string and verify that it returns what you have set in the MySQL configuration (see Connect to a MySQL Database). So from the shell prompt, just type in:
>> echo Yii::app()->db->connectionString; 

It should return something similar to the following:
mysql:host=localhost;dbname=<db-name>

This will show that the db application component is configured correctly and available for use in your web applicaiton.

*Note: To exit from shell, just type exit from the prompt.

Monday, December 9, 2013

Connect to a MySQL Database in Yii

Configuring MySQL Database in Yii

Before we continue the discussion with the other features in Gii, let me show you how to configure your Yii Web Application to connect to a MySQL database. Yii's Data Access Objects (DAO) was built on top of the PHP Data Objects (PDO) extension. All the supported database management systems (DBMS) are encapsulated behind a single uniform interface. This means that the code can remain database independent and the application developed using Yii DAO can be easily switched from one DBMS to another without the need for modification.

Let us assume that we are using MySQL Database. You must open the /protected/config/main.php file and uncomment the MySQL script below:

'db'=>array(
            'connectionString' => 'mysql:host=localhost;dbname=<database-name.',
            'emulatePrepare' => true,
            'username' => '[your-db-username]',
            'password' => '[your-db-password]',
            'charset' => 'utf8',
        ),

Also, do not forget to comment the SQL connection script that was configured once the web application was created via yiic. See the script below
/*
'db'=>array(
            'connectionString' => 'sqlite:'.dirname(__FILE__).'/../data/testdrive.db',
*/

Gii: Controller Generator

Welcome to the Yii Code Generator

With Gii configured and enabled, you may access Gii by navigating via http://localhost/<name_of_application>/index.php?r=gii. After successful entry of your password (unless you specified that a password should not be used, see Enabling Gii), you are presented with a menu page listing Gii's main features.


Controller GeneratorYou can try to create a new controller, so click on the Controller Generator menu item. This will bring you to a form that allows you to fill out the relevant details to create a new Yii controller class. You must fill out the Controller ID value and add an action ID value. Then click on the preview button, this will show you the files to be generated once you click on the generate button. See the screenshot below:


In addition to the controller class, Gii is also going to create a view file for each of the Action IDs that you have specified. You should notice that if message is the Controller ID then the corresponding class file will be named MessageController.php. Similarly, if you provide an Action ID value of hello, you can expect to have a method name in the controller called actionHello.

We will tackle more details about actions and controllers in future posts.

Friday, November 29, 2013

Enabling Gii

Automatic Code Generation

From version 1.1.12, Yii includes a web-based code generation tool called Gii. It does supercedes the previous but still useful tool called yiic, the shell generation tool that run on the command line (see Creating your Web Application with yiic). 

Enable Gii

To use Gii, you must modify the application configuration located at protected/config/main.php. To enable Gii, you must uncomment the gii module. The code auto generated by yiic (see Creating your Web Application with yiic) already added the Gii configuration, but it is commented out. All you need to do is uncomment and also add you own password as shown below: 

'modules'=>array(
// uncomment the following to enable the Gii tool
/* <- remove this to enable Gii
'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'),
),
*/ <- remove this to enable Gii
),

**Note** you can specify the password value as false then the module will not require a password. Since the ipFilters property is specified to only allow access to the localhost machine, it is safe to
set the password to false for you local development environment.

You can now navigate to the tool via http://localhost/<name_of_application>/index.php?r=gii

HAPPY DAYS!!!

Wednesday, November 27, 2013

Creating your Web Application with yiic

Command Line Tool

To create your new web application in yii, you need to use this powerful little tool called yiic. Yiic, is a command-line tool that you can use to quickly start a brand new Yii application. This tool is not mandatory to start a Yii application, but this tool allows you to save time and assures you of a correct directory and file structure.

In order to use this tool, you need to open up your command line and navigate to the directory you want to create your application's directory structure. 

For demonstration purposes, we will assume the following:
  • YiiDir is the name of the directory where you placed the Yii framework files. (see How to Install Yii)
  • WebDir is the document root of your web server.
From the command line, go to WebDir and execute the yiic command
  • Linux
    • % YiiDir/framework/yiic webapp <name_of_application>
  • Windows
    • C:\WebDir\> YiiDir\framework\yiic webapp <name_of_application>
After pressing the Return key, this message will be displayed:

     Create a Web application under 'WebDir/<name_of_application>'? [Yes|No]
     Type in Yes, press Return key.

                 mkdir /WebRoot/helloworld
                 mkdir /WebRoot/helloworld/assets
                 mkdir /WebRoot/helloworld/css
            generate css/bg.gif
            generate css/form.css
            generate css/main.css

           Your application has been created successfully under /Webroot/<name_of_application>.

Now your new web application has been created and the directories and files have been generated to provide a skeleton for a default Yii application. Let's see the list of directories and files below:
  • index.php - Web application entry script file
  • index-test.php - Entry script file for loading a test configuration
  • assets/ - Contains published resource files
  • css/ - Contains the CSS files
  • images/ - Contains the image files
  • themes/ - Contains the application themes
  • protected/ - Contains the protected (private) application files
Make sure your web server is running and you should be able to open up your browser and go to the URL http://localhost/<name_of_application>/index.php. Once you see the My Web Applicaiton page then you are good to go.

HAPPY DAYS!!!

Tuesday, November 26, 2013

How to Install Yii


Prerequisites

Prior to installing Yii, you must configure your application development environment as a web server being able to support PHP 5.1.0 or above. Yii has been tested with Apache HTTP server on Windows and Linux operating system. My own application development environment runs on Windows 7 64-bit. I installed Apache HTTP server and MySQL server using XAMPP for Windows

*Note: Avoid installing Skype in your web application development environment, this will conflict with the port (port 80) that Apache uses and Skype uses for incoming connections. If Skype is needed, just go to Skype top-menu>Tools>Options>Advance>Connections and uncheck the box “Use port 80 and 443 as alternatives for incoming connections" 

Basic Yii installation is very easy. Just follow these basic steps:
  1. Download the latest version of the Yii framework from http://www.yiiframework.com/download/.
  2. Unpack the downloaded file to your web root folder (Ex. In XAMPP, its C:\XAMPP\htdocs\yii).
You should see the following high level directories and files:
  • CHANGELOG
  • LICENSE
  • README
  • UPGRADE
  • demos/
  • framework/
  • requirements/
Now that the framework has been unpacked, it is advised that you check and verify if your environment satisfies all the requirements of using Yii. Simply point your browser to the index.php script under the requirements folder. It may look like this:

http://localhost/yii/requirements/index.php

See the screenshot of my results below:


As long as there is no Failed result, then you have successfully installed Yii.

Happy Days!!!!

Yii, History and Background

History

On December 3, 2008, the Yii framework was formally released. Yii, pronounced as "Yee" or [ji] and an acronym for "Yes it is!", is an open-source, object-oriented , component-based Model-View-Controller PHP web application framework. Founded by Qiang Xue, who previously developed and maintained the PRADO framework, initially conceptualized Yii as to fix some drawbacks to the PRADO framework. But Yii continued to draw positive attention and its popularity and adoption continues to grow when compared to other PHP-based frameworks.

Features

  • Model-View-Controller design pattern
    • This allows separation of concerns (SOC)
  • Data Access Objects (DAO), Query Builder, Active Record and DB Migration
    • Avoid the complexity of re-writing SQL statements
  • AJAX-enabled widgets
    • Integrated with jQuery.
  • Web services
    • Automatic generation of WSDL service specifications and management of Web service request handling
  • Error handling and logging
    • Errors are more presentable, categorized, filtered and manageable
  • Automatic code generation
    • Quickly generate code for form input, CRUD and others
  • Authentication and authorization
    • It supports role based access control (RBAC)
  • Form input and validation
    • Validation comes built in
  • Skinning and Theming
    • Quickly switch look and feel
  • Layered caching scheme
    • Supports data caching, page caching, fragment caching and dynamic content.
  • Unit and functionality testing
    • Based on PHPUnit and Selenium.
  • Detailed documentation
    • Every method and property is well documented, accessible from both books and the internet
  • Extension library
    • User contributed extensions are made available
  • Internationalization (I18N) and localization (L10N)
    • Supports message translation, date and time formatting and number formatting
  • Security
    • Equipped with many security measures to prevent attacks as SQL injection, XSS, CSRF and cookie tampering
  • Third party code friendly
    • Works well with PEAR or Zend framework and others.