The Yii Framework – Larry Ullman
This is a copy of the Larry Ullman series ‘Learning the Yii Framework’. See
http://www.larryullman.com/2009/06/18/introduction-to-the-yii-framework/.
1. Introduction to the Yii Framework
In 2009, I had three decent-size Web sites to develop, so I thought I might try using a PHP framework for the first time, instead of coding everything from scratch. I’ve used Ruby on Rails for Web development before,
so I’m comfortable with frameworks and the MVC architecture, but I wanted to educate myself on PHP
frameworks. After researching a handful of frameworks, and after an unsatisfying attempt to use Zend Framework, I finally settled on, and really came to appreciate the Yii Framework. At the time, the Yii Framework was still quite new, and there are still bugs to be worked out (for the more advanced stuff), but
Yii works so well that it’s very easy to use. In this first of several posts on the Yii Framework, I just discuss
setting up and testing Yii.
(Note: In October 2010, I’ve updated this entire series to reflect changes in Yii since this series was
written, and to take into account feedback provided through the comments. Some outdated material will be crossed out, but left in to reflect how things have changed since the series was begun in June 2009.)
The first thing you need in order to use the Yii Framework is access to a Web server with PHP installed, of
course. But if you’re reading this, I’m going to assume you have access to a PHP-enabled server. Note that
the Yii Framework does require PHP 5.1 or above. Fortunately, the framework will test your setup for you!
Start by downloading the latest stable version of the Yii Framework. At the time of this writing, that’s 1.0.6
1.1.4. The file you download will be named something like yii-version.release.ext and is only around 2MB. Expand the downloaded file to create a folder of stuff:
CHANGELOG, LICENSE, README, and UPGRADE text documents demos folder framework folder requirements folder
You should read the README and LICENSE docs, of course, but the folders are most important here. The demos folder contains four Web applications written using Yii: a blog, the game Hangman, a basic “Hello,
World!”, and a phone book. The demos are great for seeing working code as you’re trying to write your own.
The framework folder is what’s required by any Web site using Yii. The requirements folder is something
simple and brilliant…
I also assume that you already know what the Web root directory is on your computer or server: this is the folder where your URL points to. In other words, when you go to http://localhost or http://www.example.com in your Web browser, it grabs documents out of the Web root folder. Going with Yii’s conventions, I’ll call this WebRoot. Create a new folder in your WebRoot called yii, and copy the framework and requirements folders there. Then go to yourURL/yii/requirements in your Web browser (for example, http://localhost/yii/requirements). You should see a report as to whether or not your setup meets the minimum requirements.
Assuming your setup passed all the requirements, you’re good to go on. Note that you don’t necessarily
need every extension: you just really need the Yii Framework requirements, PDO, and the PDO extension for
the database you’ll be using. (If you’re not familiar with it, PDO is a database abstraction layer, making your
Web sites database-agnostic.)
In my next post, I’ll show you how to use the command-line Yii tools to create your first Web application. It’s pretty sweet stuff and is the closest thing to Ruby on Rails that I’ve seen (which I consider to be a very good
thing). Subsequent posts will walk you through developing a Yii-based application. Use the series links at the top and bottom of this post to navigate the series. You may also want to read my posts on the MVC
2. Getting Started with the Yii Framework
Many, many moons ago I wrote a post introducing the Yii framework. It’s a framework for creating Web
applications using PHP 5 (or greater) that I’ve really liked since I originally started with it. Ruby on Rails was
the first Web development framework I personally used (back in 2005) and Zend was the first PHP framework. I love the former, and Yii is quite like it in many ways, but I never really took to Zend. In that first
post, I discussed just downloading and testing Yii; here I’ll walk through creating the beginnings of a Web
application.
(Note: In October 2010, I’ve updated this entire series to reflect changes in Yii since this series was
written, and to take into account feedback provided through the comments. Some outdated material will be crossed out, but left in to reflect how things have changed since the series was begun in June 2009.)
For the specific example, I’ll use an employees-departments Web application, with a list of departments and a list of employees, each employee being in only one department. This is a classic go-to example, as it’s easy to understand, practical, uses more than one database table, and is extensible in many ways. To start,
though, you’ll use the command-line Yii tools to create the application’s frame. If you’ll be putting the site on
a server that you do not have command-line access to, then you should install a complete Web server (Apache, PHP, MySQL, etc.) on your computer, run through these steps, then upload the finished project
once you’ve completed it. If you don’t already have a Web server on your computer, I’d recommend using
XAMPP (for Windows) or MAMP (for Mac), both of which are free and extremely easy to use.
The first thing you’ll need to do is make sure you have the latest version of the Yii framework. My first post discusses how to get it. Then you’ll want to put the framework folder in a logical location on the server. You don’t need to put it within the Web directory (arguably, you shouldn’t) but nearby, like in the directory
below makes the most sense. For example, on my setup, the htdocs folder is the Web root, which is to say that http://www.example.com points there.
My directory structure.
Tip: If you’re going to be using Yii for multiple sites on the same server, place the framework folder in a logical directory relative to every site. That way, when you update the framework, you’ll only need to
replace the files in one place. Next, you’ll need to get yourself into a command-line environment, like a DOS window/console on Windows or the Terminal application on Mac OS X (and some versions of Linux). Then move yourself into the framework directory. On my server, this means executing this line:
cd /Users/larryullman/Sites/YiiBlogSite/framework
You’ll need to change the particulars to match your setup.
The next step is to tell the yiic application, found in the framework folder, to create a new site. The syntax is yiic webapp path/to/directory
But before you even begin to use this command, let me explain it a bit, as it’s very important and can be complicated. The yiic file is an executable that runs using the computer’s command-line PHP and that really
just invokes the yiic.php script. You may be able to call it using just yiic or using ./yiic (i.e., run the yiic
command found in the current directory). Or you can more explicitly call either script using php yiic or php yiic.php. Or you may need to indicate the PHP executable to be used: C:\php\php.exe yiic. You should try the variations on this command, as applicable to your computer, just to make sure you can invoke yiic, prior to trying to create the Web application.
Besides properly executing the yiic script, another gotcha can arise if you have more than one version of PHP installed on your computer. To confirm the version being used, run php -v (again, you may need to provide the full path to the PHP executable). On Mac OS X and Unix, you can use which php to reveal the PHP executable being used by the command php. These steps can help solve confusing problems. For example, on my Mac, I use MAMP Pro for PHP and MySQL Web development, but when I execute PHP through the
command-line, I’ll actually be invoking the PHP installed with the operating system. This can be a problem,
as the different versions of PHP may or may not meet the Yii requirements outlined in my first post. I know when I first tried this, the command-line PHP (installed with the OS) did not support the required PDO extension, even though the Web version of PHP (in MAMP Pro) did. My solution was to explicitly name my
MAMP PHP executable when running yiic: /Applications/MAMP/bin/php5.3/bin/php yiic.
Once you know you’ve figured out the proper syntax for invoking yiic, you follow that by webapp, which is the command for “create a new Web application”. Follow this with the path to the Web application itself.
Given the directory structure already indicated (in the above figure), the command would be just ./yiic webapp ../htdocs Or php yiic webapp ../htdocs Or whatever variation on that you need to use.
You’ll be prompted to confirm that you want create a Web application in the given directory. Enter Y (or Yes)
and press Return. After lots of lines of responses, you should see a message saying that the application has successfully been created. To confirm this, load the site in your browser (by going through a URL, of course):
The Auto-Generated, Basic Yii Application As for functionality, the generated application already includes:
a home page with further instructions a contact form, complete with CAPTCHA a login form
the ability to greet a logged-in user by name logout functionality
It’s a very nice start to an application, especially considering you haven’t written a line of code yet. Do note that the contact form will only work once you’ve edited the configuration to provide your email address. For
the login, you can use either (username/password): demo/demo or admin/admin. Lastly, the exact look of the application may differ from one version of the Yii framework to another.
In terms of files on the server, within the application directory (htdocs, for me), you’ll find:
assets css images index-test.php index.php protected themes
The assets folder will be used by the Yii framework primarily for jQuery (the JavaScript framework) integration. The css and images folders are obvious. The entire site will also be run through one of the two
index files (more on this in the next post). The protected folder is actually the most important one: you’ll
edit code found in that folder to change the look and behavior of the site. And themes allows you to create
variations on the site’s template, just like themes in a WordPress blog.
Tip: The assets folder must be writable by the Web server or else odd errors will occur. This
shouldn’t be a problem unless you transfer a Yii site from one server to another and the permissions aren’t
correct after the move.
So that’s the start of a Yii-based Web application. For every site you create using Yii, you’ll likely go through these steps. In the next post, I’ll start demonstrating how you can configure the application, and alter it for
an employees-departments example.
3. Configuring Yii
This is the third post in my series on Yii, my favorite PHP framework. In the first, I show how to download and test the framework itself. In the second, I show how to create a basic Web application. The end of that
post also discusses the files and folders in the application directory. You’ll want to be familiar with those as you go forward. In this post, I discuss how you’ll want to configure your Yii-based application, including
handling errors, adding components, and establishing a database connection. This post does assume you
have an existing application to work with; if you don’t, follow the steps in the previous two posts.
(Note: In October 2010, I’ve updated this entire series to reflect changes in Yii since this series was
written, and to take into account feedback provided through the comments. Some outdated material will be crossed out, but left in to reflect how things have changed since the series was begun in June 2009.)
There are a couple of ways you can configure how your Yii application behaves. For the most part, you’ll do this through the protected/config/main.php file, but first I want to talk about the index.php file, created in
the root of your Web application directory. This is a “bootstrap” file, meaning that all user interactions
actually go through it. For example, showing an employee record might be through the URL www.example.com/index.php/employee/show/id/34 and updating a department record might involve submitting a form to www.example.com/index.php/department/update/id/3. Both URLs request just that one PHP script.
The index.php file is generated when you use the command-line yiic script. There’s only seven lines of noncommented code in it. The first identifies the location of the Yii framework:
$yii=dirname(__FILE__).'/../framework/yii.php';
The path indicated should already be correct (because it’s created when the framework is used to make the
application), but you can change this value if you move the framework or the index file. The second line identifies where the configuration file is: $config=dirname(__FILE__).'/protected/config/main.php'; The default behavior is to put the protected directory, where all the application files reside, in the same directory as the index file. My inclination is to move it outside of the Web directory, like so:
Modified Yii Layout In such a case, I edit my index.php file to read: $config= '../protected/config/main.php';
Note that it’s perfectly reasonable to move the location of your application files (i.e., the protected folder),
but you should not change the names or structure of the folders found within the protected directory.
Tip: Moving the protected folder outside of the Web root directory is just an extra security precaution. It’s not required, and you may not want to bother with the change, especially as you’re just getting started.
The next line of code turns on debugging mode: defined('YII_DEBUG') or define('YII_DEBUG',true);
You’ll want debugging enabled when developing a site, but disabled once live. To disable debuggin, remove
or comment out that line. I normally just comment it out, so that I can re-enabled debugging later. Or you can change it to something like this, so that you can add debugging to a page on the fly:
if (isset($_GET['debug'])) define('YII_DEBUG', true); If you do that, then to debug any page on the fly, change the URL from, for example,www.example.com/index.php/site/contact to www.example.com/index.php/site/contact/debug/true.
The next line of code dictates how many levels of “call stack” are shown in a message log:
defined('YII_TRACE_LEVEL') or define('YII_TRACE_LEVEL',3);
The “call stack” is a history of what files, functions, etc., are included, invoked, and so forth. With a
framework, the simple loading of the home page could easily involve a dozen actions. In order to limit the logged (i.e., recorded) data to the most recent, useful information, the call stack is limited by that line to just the most recent three actions.
The last two lines of the bootstrap file include the framework and start the application. Don’t mess with
these! require_once($yii); Yii::createWebApplication($config)->run();
And that’s really all there is to do in the index.php page. As of Yii 1.1., the framework creates another
bootstrap file: index-test.php. It is exactly the same as index.php, except that index-test.php includes a different configuration file: /protected/config/test.php instead of /protected/config/main.php. However,
the test configuration file just includes the main configuration file, then also enables the CDbFixtureManager component, which is used for unit testing. The index-test.php file also omits the call stack limitation.
Most of the configuration occurs in the main.php configuration file, found within the protected/config
directory (see the above image). There’s also a console.php config file, but that’s for a command-line version of the application. I won’t discuss that here, but you would edit it if you have command-line scripts
associated with your application. The configuration file returns a multi-dimensional array of information, some of which is pre-defined. You do want to make sure that the proper syntax is maintained as you edit this, so be careful in matching parentheses and using commas where necessary.
For starters, you’ll want to change the name of the application, which is used in the default HTML design, in
page titles, and so forth:
'name'=>'Wicked Cool Yii Site',
Next, under the modules section of the returned array, you should enable Gii. Gii is a Web-based tool that
you’ll use to generate Models, Views, and Controllers for the application. To enable Gii, just remove the
comment tags—/* and */—that surround this code:
'gii'=>array(
'class'=>'system.gii.GiiModule', 'password'=>'SECURE',
),
Also enter a secure password in the code, one that only you will know. Tip: Gii was added to Yii in version 1.1.2, and it replaces functionality available using the command-line Yii tools.
Moving down the file, in the components section of the returned array, you’ll probably want to enable
urlManager. Just remove the comment code that surround the following:
'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>',
),
),
This component changes URLs to be more search engine and user-friendly. For example, the default URL for a page could be something like www.example.com/index.php?r=site/contact, but urlManager will turn that
into www.example.com/index.php/site/contact. If you want to take this further, it’s possible to configure
urlManager, along with an Apache .htaccess file, so that index.php no longer needs to be part of the URL.