Quickstart – Creating an application

Exclusive offer: get 50% off this eBook here
Instant Yii 1.1 Application Development Starter [Instant]

Instant Yii 1.1 Application Development Starter [Instant] — Save 50%

Get started with building attractive PHP web applications with the Yii framework with this book and ebook

$12.99    $6.50
by Jacob Mumm Mark Safronov | September 2013 | Open Source Web Development

This article by Jacob Mumm and Mark Safronov, the authors of Instant Yii 1.1 Application Development Starter, we will create an application. The Yii website contains, among its wonderful documentation, a tutorial on how to build a basic blog application, which is one of the included demos in the framework source. It's in Tutorials The Yii Blog Tutorial section. Direct URL is http://www.yiiframework.com/doc/blog/.

(For more resources related to this topic, see here.)

Step 1 – Planning the workflow

When you'll be writing a real application, you should start with the requirements to application functionality. For the blog example, they described in the Getting Started: Requirements Analysis section, at the very beginning of the tutorial. Direct URL is http://www.yiiframework.com/doc/blog/1.1/en/start.requirements.

After you have written all the desired features, you basically start implementing them one by one. Of course, in serious software development there's a lot of gotchas included but overall it's the same.

Blog example is a database driven application, so we need to prepare a database schema beforehand. Here's what they came up with for the blog demo.

This image is a verbatim copy from the blog example demo. Note that there are two links missing. The posts table have tags field which is the storage area for tags written in raw and is not a foreign key to tags table. Also author field in comment should really be the foreign key to user table. Anyways, we'll not cover the actual database generation, and suggest you can do it yourself. The blog tutorial at the Yii website has all the relevant instructions addressed to total newbies.

Next in this article we will see how easy it is with Yii to get a working user interface by which one will be able to manipulate our database.

Step 2 – Linking to the database from your app

Once you design and physically create, the database in some database management system like MySQL or maybe SQLite, you are ready to configure your app to point to this database. The skeleton app generated by the ./yiic webapp command needs to be configured to point to this database. To do this, you need to set a db component in the main config file located at protected/config/main.php. There is a section that contains an array of components. Below is the setup for a MySQL database located at the same server as the web application itself. You will find a commented-out template for this already present when you generate your app.

/protected/config/main.php

'components'=>array(
/* other components */
'db'=>array(
'connectionString' => 'mysql:host=localhost;dbname=DB_NAME,
'emulatePrepare' => true,
'username' => YOUR_USERNAME,
'password' => YOUR_PASSWORD,
'charset' => 'utf8',
),
/* other components */
),

This is a default component having a class CDbConnection and is used by all of our ActiveRecord design patterns which we will create later. As with all application components, all configuration parameters corresponds to the public properties of the component's class, so, you can check the API documentation for details.

By the way, you really want to understand more about the main application config. Read about it in the Definitive Guide to Yii at the official website, at Fundamentals | Application | Application Configuration. Direct URL is http://www.yiiframework.com/doc/guide/1.1/en/basics.application#application-configuration.

Just remember that all configuration parameters are just properties of CWebApplication object, which you can read about it the API documentation, direct URL is
http://www.yiiframework.com/doc/api/1.1/CWebApplication.

Step 3 – Generating code automatically

Now that we have our app linked up to a fully built database, we can start using one of Yii's greatest features: automatic code generation. To get started, there are two types of code generation that are necessary:

  • Generate a model classes based on the tables in your database
  • Run the CRUD generator that takes a model and sets up a corresponding controller and set of views for basic listing, creating, viewing, updating and deleting from the table

Console way

There are two ways to go about automatic code generating. Originally, there was only the yiic tool used earlier to create the skeleton app. For the automatic code generation features, you would use yiic shell index.php command, which would bring up a command-line interface where you could run subcommands for modeling and scaffolding.


$ /usr/local/yii/framework/yiic shell index.php
Yii Interactive Tool v1.1 (based on Yiiv1.1.13)
Please type 'help' for help. Type 'exit' to quit.
>> model Post tbl_post
generate models/Post.php
unchanged fixtures/tbl_post.php
generate unit/PostTest.php
The following model classes are successfully generated:
Post
If you have a 'db' database connection, you can test these models now
with:
$model=Post::model()->find();
print_r($model);

>> crud Post
generate PostController.php
generate PostTest.php
mkdir /var/www/app/protected/views/post
generate create.php
generate update.php
generate index.php
generate view.php

As you can see, this is a quick and easy way to perform the model and crud actions. The model command produces just two files:

  • For your actual model class
  • For unit tests

The crud command creates your controller and view files.

Gii

Console tools may be the preferred option for some, but for developers who like to use graphical tools, there is now solution for this, called Gii.

To use Gii, it is necessary to turn it on in the main config file: protected/config/main.php. You will find the template for it already present, but it is commented out by default. Simply uncomment it, set your password, and decide from what hosts it may be accessed. The configuration looks like this:

'gii'=>array(
'class'=>'system.gii.GiiModule',
'password'=>'giiPassword',

// If removed, Gii defaults to localhost only.
// Edit carefully to taste.
'ipFilters'=>array('127.0.0.1','::1'),

// For development purposes,
// a wildcard will allow access from anywhere.
// 'ipFilters'=>array('*'),
),

Once Gii is configured, it can be accessed by navigating to the app URL with ?r=gii after it. For example, http://www.example.com/index.php?r=gii. It will begin with a prompt asking for the password set in the config file. Once entered, it will display a list of generators. If the database is not set in the config file, you will see an error when you attempt to use one.

The first most basic generator in Gii is the model generator. It asks for a table name from the database and a name to be used for the PHP class.

Note that we can specify a table name prefix which will be ignored when generating the model class name. For instance, the blog demo's user table is tbl_user, where the tbl_ is a prefix. This feature exists to support some setups, especially common in shared hosting environments, where a single database holds tables for several distinct applications. In such an environment, it's a common practice to prefix something to names of tables to avoid getting into naming conflict and easily find tables relevant to some specific application. So, as this prefixes don't mean anything in the application itself, Gii offers a way to automatically ignore them. Model class names are being constructed from the remaining table names by the obvious rules:

  • Underscores are converted to uppercasing the next letter
  • The first letter of the class name is being uppercased as well.

The first step in getting your application off the ground is to generate models for all the entity tables in your database. Things like bridge tables will not need models, as they simply relate two entities to one another, rather than actually being a distinct thing. Bridge tables are being used for generating relations between models, expressed in the relations method in model class.

For the blog demo, basic models are User, Post, Comment, Tag, and Lookup.

The second phase of scaffolding is to generate the CRUD code for each of these models. This will create a controller and a series of view templates. The controller (for example. PostController) will handle routing to actions related to the given model. The view files represent everything needed to list and view entities, as well as the forms needed to create and update individual entities.

Summary

In this article we created an application by following a series of steps such as planning the workflow, linking to the database from your app, and generating code automatically.

Resources for Article :


Further resources on this subject:


Instant Yii 1.1 Application Development Starter [Instant] Get started with building attractive PHP web applications with the Yii framework with this book and ebook
Published: June 2013
eBook Price: $12.99
See more
Select your format and quantity:

About the Author :


Jacob Mumm

Jacob Mumm is a web developer from Upstate New York specializing in PHP and JavaScript web applications. He has worked for non-profit organizations, advertising companies, and schools using tools such as Drupal, jQuery (including UI and Mobile), AngularJS, and the Yii Framework. His interests range from outdoor activities such as hiking, camping, and kayaking, to organic food and gardening as part of a holistic, sustainable lifestyle, all the while staying up to date with the latest gadgets, gizmos, and web application technologies.

One of the things he deeply enjoys is talking to people about the things for which he has the most passion. He likes to share his knowledge and experience with others. Even when incomplete, Jacob finds the act of consolidating his thoughts on a subject a great way to solidify his own understanding or to discover places where he needs to investigate further.

Mark Safronov

Mark Safronov is a professional web application developer from the Russian Federation with experience and interest in a wide range of programming languages and technologies. He has built and participated in building different types of web applications, from purely computational ones to full-blown e-commerce sites. He is also a proponent of following the current best practices for test-first development and clean and maintainable code.

He is currently employed at Clevertech, and is working on Yii-based PHP web applications and maintaining a quite popular YiiBooster open source extension.

Back in 2008, he translated the book Visual Prolog 7.1 for Tyros by Eduardo Costa in to Russian.

Books From Packt


Yii Application Development Cookbook - Second Edition
Yii Application Development Cookbook - Second Edition

Yii Rapid Application Development Hotshot
Yii Rapid Application Development Hotshot

Agile Web Application Development with Yii1.1 and PHP5
Agile Web Application Development with Yii1.1 and PHP5

Web Application Development with Yii and PHP
Web Application Development with Yii and PHP

Yii 1.1 Application Development Cookbook
Yii 1.1 Application Development Cookbook

CakePHP 1.3 Application Development Cookbook
CakePHP 1.3 Application Development Cookbook

HTML5 iPhone Web Application Development
HTML5 iPhone Web Application Development

Opa Application Development
Opa Application Development


No votes yet

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
1
R
5
5
1
T
Enter the code without spaces and pay attention to upper/lower case.
Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software