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

Chapter 2: Getting Started

The real pleasures and benefits of Yii are quickly revealed by simply using it. In this chapter, we will see how the concepts introduced in the previous chapter, Meet Yii, are manifested in an example Yii application. In the spirit of Yii's philosophy to follow conventions, we will write a Hello, World! program to try out this new framework.

In this chapter, we will cover:

  • Yii Framework installation
  • Creating a new application
  • Creating controllers and views
  • Adding dynamic content to view files
  • Yii request routing and linking pages together

Before we can use it we need to first install the framework. Let's do that now.

Installing Yii

Prior to installing Yii, you must configure your application development environment as a web server capable of supporting PHP 5.1.0 or higher. Yii has been thoroughly tested with Apache HTTP server on Windows and Linux operating systems. It may also run on other web servers and platforms, provided PHP 5 is supported. There are myriad free resources available on the Internet to assist you in getting your environment configured with a PHP 5 compatible web server. We assume the reader has previously engaged in PHP development and has access to such an environment. We will leave the installation of a web server and PHP itself as an exercise to the reader.

The basic Yii installation is almost trivial. There are really only two necessary steps:

  1. Download the Yii Framework from http://www.yiiframework.com/ download/.
  2. Unpack the downloaded file to a web-accessible folder.

After installation, it is advised that you verify that your server satisfies all of the requirements for using Yii and to ensure the installation was a success. Luckily, doing so is easy. Yii comes with a simple requirement checking tool. To invoke the tool and have it verify the requirements for your installation, simply point your browser to:http://yourhostname/path/to/yii/requirements/index.php

There are several versions of Yii from which to choose when downloading the framework. We will be using version 1.1.2 for the purposes of this book, which is the latest stable version as of the time of writing. Though most of the sample code should work with any 1.1.x version of Yii, there may be some subtle differences if you are using a different version. Please use 1.1.2 if you are following along with the examples.

The following screenshot shows the results we see for our configuration:

Using the Requirement Checker is not itself a requirement for installation, but it is certainly recommended to ensure proper installation. As you can see, not all of our results under the Details section received a Passed status, as some display a Warning. Of course, your configuration will most likely be slightly different from ours and consequently, your results may slightly differ as well. That is okay. It is not necessary that all of the checks under the Details section pass, but it is necessary to receive the following message under the Conclusion section:

Your server configuration satisfies the minimum requirements by Yii.

Installing a database

Throughout this book, we will be using a database to support many of our examples and the applications that we will be writing. In order to properly follow along with this book, it is recommended you install a database server. Though you can use any database that is supported by PHP with Yii, if you want to use some of built-in database abstraction layers and tools within Yii, you will need to use one that is supported by the framework. As of version 1.1, those are:

  • MySQL 4.1 or later
  • PostgresSQL 7.3 or later
  • SQLite 2 and 3
  • Microsoft SQL Server 2000 or later • Oracle

Now that we have installed the framework, and we have verified that we have met the minimum requirements, let's create a brand new Yii web application.

Creating a new application

To create a new application, we are going to use a little powerhouse of a tool known as yiic that comes packaged with the framework. This is a command-line tool that one can use to quickly jumpstart a brand new Yii application. It is not mandatory to use this tool, but it saves a lot of time and guarantees that the proper folder and file structure is in place.

To use this tool to create your first Yii application, open up a shell window, and navigate to a place in your filesystem where you will want to create your application's folder structure. For the purpose of this demo application, we will assume the following:

  • YiiRoot is the folder where you have installed Yii
  • WebRoot is configured as the document root of your web server
  • From your command line, change to your WebRoot folder and execute the following:
      % cd Webroot
      % YiiRoot/framework/yiic webapp demo
      Create a Web application under '/WebRoot/demo'? [Yes|No]
             mkdir /WebRoot/demo
             mkdir /WebRoot/demo/assets
             mkdir /WebRoot/demo/css
             generate css/bg.gif
             generate css/form.css
             generate css/main.css

Your application has been created successfully under /Webroot/demo. The webapp command is used to create a brand new Yii web application. It takes just a single argument to specify either the absolute or relative path to the folder in which the application should be created. The result is the generation of all the needed folders and files to provide a default Yii web application skeleton.

Now we can change into the newly created demo folder and look at what was created for us:

% cd demo %
assets/    images/    index.php    themes/
css/    index-test.php    protected/

A description of the high-level items that were automatically created is shown as follows:

demo/ index.php    Web application entry script file
index-test.php entry script file for the functional tests
assets/    containing published resource files
css/ images/ themes/ protected/
containing CSS files containing image files containing application themes
containing protected application files

With the execution of one simple command from the command line, we have created all the folder structure and files needed to immediately take advantage of Yii's sensible default configuration. All of these folders and the files, along with the subfolders and files they contain, can look a little daunting at first glance. However, we can ignore most of them as we are getting started. All these folders and files are actually a working web application. The yiic command has populated the application with enough code to establish a simple home page, a typical Contact Us page to provide an example of a web form, and a login page with enough autogenerated code to demonstrate basic authorization and authentication in Yii. If your web server supports the GD2 graphics library extension, you will also see a CAPTCHA widget on the Contact Us form, and the application will have the corresponding validation for this form item.

As long as your web server is running, you should be able to open up your browser and navigate to http://localhost/demo/index.php. Here you will be presented with a My Web Application home page along with the friendly greeting Welcome to My Web Application, followed by some helpful information on the steps to be taken next. The next screenshot shows this example home page:

You'll notice that there is a working application navigation bar along the top of the page. From left to right there is: Home, About, Contact, and Login. Let's explore by clicking around. Clicking on the About link provides a simple example of a static page. The Contact link will take you to the Contact Us form that was mentioned before, along with the CAPTCHA input field in the form (again, you will only see the CAPTCHA field if you have the GD graphics extension as part of your PHP configuration).

The Login link will take you to a page displaying a login form. This is actually working code with form validations, as well as username and password credential validation and authentication. Using either demo/demo or admin/admin as the username/password combination will get you logged into the site. Try it out. You can try a login that will fail (any combination other than demo/demo or admin/ admin), and see the error validation messages display. After successfully logging in, the Login link in the header changes to a Logout(username) where username is either demo or admin, depending on which username you used to login. It is amazing that so much has been accomplished without having to do any coding.

Hello, World!

All of this autogenerated code will start to make more sense once we walk through a simple example. To try out this new system, let's build that Hello, World! program we promised at the start of this chapter. A Hello, World! program in Yii will be a simple web page application that sends this very important message to our browser.

We have already discussed about Yii being a Model-View-Controller framework in Chapter 1, Meet Yii,. A typical Yii web application takes in an incoming request from a browser, parses information in that request to find a controller, and then calls an action within that controller. The controller can then invoke a particular view to render and return content to the user. If dealing with data, the controller may also interact with a model to handle all the Create, Read, Update, and Delete (CRUD) operations on that data. In our simple Hello, World! application, all we will require is the code for a controller and a view. We are not dealing with any data, so a model will not be needed. Let's begin our example by creating our controller.

Creating the controller

As we did when we created the initial application, we will again call on the yiic command to help us create our controller. In this case, we are going to use the yiic shell command to start the application within an interactive shell in which we can invoke other commands. To start the shell, navigate to the root of your demo application by running the following command:

%cd /Webroot/demo

Then execute yiic with the following shell command:

%YiiRoot/framework/yiic shell
Yii Interactive Tool v1.1
Please type 'help' for help. Type 'exit' to quit. 

If you have navigated into your web application folder, you can also envoke the yiic command-line tool by referencing the relative path protected/yiic rather than the fully qualified path to where Yii is installed. So, the equivalent way to start the shell from within the folder would be: % protected/yiic shell

You are now at the prompt within the interactive shell. You can type help to see a list of commands available to you within this shell:

>> help
At the prompt, you may enter a PHP statement or one of the following commands:
 - controller
 - crud
 - form
 - help
 - model
 - module
Type 'help <command-name>' for details about a command.

We see there are several command options available. The controller command looks like the one we want, as we want to create a controller for our application. We can find out more about this command by typing help controller from the shell prompt. Go ahead and type that in. It provides usage, a general description, parameter descriptions, and some examples.

>> help controller
    controller <controller-ID> [action-ID] ...
    This command generates a controller and views associated with the specified actions.
  * controller-ID: required, controller ID, e.g., 'post'.
     If the controller should be located under a subdirectory, 
     please specify the controller ID as 'path/to/ControllerID',
     e.g., 'admin/user'.
     If the controller belongs to a module, please specify 
     the controller ID as 'ModuleID/ControllerID' or 
     'ModuleID/path/to/Controller' (assuming the controller is under a subdirectory of that module).
  * action-ID: optional, action ID. You may supply one or several action IDs. 
     A default 'index' action will always be generated.
  * Generates the 'post' controller:
            controller post
  * Generates the 'post' controller with additional actions 'contact' and 'about':
            controller post contact about 
  * Generates the 'post' controller which should be located under
    the 'admin' subdirectory of the base controller path:
            controller admin/post
  * Generates the 'post' controller which should belong to the 'admin' module:
            controller admin/post

In the last two examples, the commands are the same, but the generated controller file is located under different folders. Yii is able to detect whether admin refers to a module or a subfolder.

So, from reading the help, it is clear that the controller command will generate the controller, actions, and the views associated with the specified actions. As our application's primary function is to display a message, let's call our controller, message, and let's name our action method after the simple message we want to display:

>> controller message helloWorld
generate MessageController.php
               mkdir /Webroot/demo/protected/views/message
        generate helloworld.php
        generate index.php
Controller 'message' has been created in the following file: 
You may access it in the browser using the following URL: 

It should respond by indicating the successful creation of the MessageController in the default protected/controllers/ folder.

This is great. With one simple command, we have generated a new controller PHP file, called MessageController.php, and it was placed properly under the default controllers folder, protected/controllers/. The generated MessageController class extends an application base class, Controller, located at protected/ components/Controller.php. This class in turn extends the base framework class, CController, so it automatically gets all of the default controller behavior. Since we specified an actionID parameter, helloWorld, a simple action was also created within MessageController called actionHelloWorld(). The yiic tool also assumed that this action, like most actions defined by a controller, will need to render a view. So, it added the code to this method to render a view file by the same name, helloworld.php, and placed it in the default folder for view files associated with this controller, protected/views/message/. Here is the code that was generated for the MessageController class:

class MessageController extends Controller
    public function actionHelloWorld()
    public function actionIndex() {

We see that it also added an actionIndex() method that simply renders a view file that was also auto-created for us at protected/views/message/index.php. As was discussed in Chapter 1, Meet Yii by convention, a request that specifies message as the controllerID, but does not specify an action, will be routed to the actionIndex() method for further processing. The yiic tool was smart to know to create a default action for us.

Try it out by navigating to http://localhost/demo/index.php?r=message/ helloWorld. You should see something similar to the following screenshot:

One final step

To turn this into a Hello, World! application, all we need to do is customize our helloWorld.php view to display Hello, World!. It is easy to do this. Edit the file protected/views/message/helloWorld.php so that it contains just the following code:

<h1>Hello, World!</h1>

Save your code, and view the page again in your browser: http://yourhostname/ index.php?r=message/helloWorld

It now displays our introductory greeting in place of the autogenerated copy, as displayed in the following screenshot:

We have our simple application working with stunningly minimal code. All we have added is one line of HTML to our helloWorld view file.

Reviewing our request routing

Let's review how Yii is analyzing our request in the context of this example application:

  1. You navigate to the Hello, World! page by pointing your browser at the following URL: http://yourhostname/demo/index.php?r=message/ helloWorld.
  2. Yii analyzes the URL. The route querystring variable indicates that the controllerID is message. This tells Yii to route the request to the MessageController class, which it finds in protected/controllers/ MessageController.php.
  3. Yii also discovers that the actionID specified is helloWorld. So, the action method actionHelloWorld() is invoked within the MessageController.
  4. The actionHelloWorld() method renders the helloWorld.php view file located at protected/views/message/helloWorld.php. And we altered this view file to simply display our introductory greeting, which is then returned to the browser.
  5. This all came together without having to make any configuration changes. By following Yii's default conventions, the entire application request routing has been seamlessly stitched together for us. Of course, Yii gives us every opportunity to override this default workflow if needed, but the more you stick with the conventions, the less time you will spend in tweaking configuration code.

Adding dynamic content

The simplest way to add dynamic content to our view template is to embed PHP code into the template itself. View files are rendered by our simple application to result in HTML, and any basic text in these files is passed through without being changed. However, any content between the tags is interpreted and executed as PHP code. This is a typical way PHP code is embedded within HTML files and is probably familiar to you.

Adding the date and time

To spice up our page with dynamic content, let's display the date and time. Open up the helloWorld view again and add the following line below the greeting text:

<h3><?php echo date("D M j G:i:s T Y"); ?></h3>

Save, and view it at the following URL: http://yourhostname/demo/index. php?r=message/helloWorld

Presto! We have added dynamic content to our application. With each page refresh, we see the displayed content changing.

Admittedly, this is not terribly exciting, but it does show how to embed simple PHP code into our view templates.

Adding the date and time, a better approach

Although this approach of embedding PHP code directly into the view file does allow for any PHP code of any amount or complexity, it is strongly recommended that these statements do not alter data models and that they remain simple, display-oriented statements. This will help keep our business logic separate from our presentation code, which is part of the agenda of an MVC architecture.

Moving the data creation to the controller

Let's move the logic that creates the time back to the controller and have the view do nothing more than display the time. We'll move the determination of the time into our actionHelloWorld() method within the controller and set the value in an instance variable called $time.

  1. First, let's alter the controller action. Currently our action in our MessageController, actionHelloworld(), simply makes a call to render our helloWorld view by executing the following code:
    Before we render the view, let's add the call to determine the time, and then store it in a local variable called $theTime. Let's then alter our call to render() by adding a second parameter which includes this variable:
    $theTime=date("D M j G:i:s T Y");
    When calling render() with a second parameter containing array data, it will extract the values of the array into PHP variables and make those variables available to the view script. The keys in the array will be the names of the variables made available to our view file. In this example, our array key time whose value is $theTime, will be extracted into a variable named $time, which will be made available in the view. This is one way to pass data from the controller to the view.
  2. Now let's alter the view to use this instance variable, rather than calling the date function itself. Open up the helloWorld view file again, and replace the line we previously added to echo the time with the following:
    <h3><?php echo $time; ?></h3>
  3. Save and view the results again at:http://yourhostname/demo/index.php?r=message/helloWorld

The next screenshot shows the end result of our Hello, World! application thus far (of course, your date and time will differ).

We have demonstrated two approaches to adding PHP generated content to the view template files. The first approach puts the data creation logic directly into the view file itself. The second approach housed this logic in the controller class, and fed the information to the view file by using variables. The end result is the same, the time is displayed in our rendered HTML file, but the second approach takes a small step forward in keeping the data acquisition and manipulation, that is business logic, separate from our presentation code. This separation is exactly what a Model-View-Controller architecture strives to provide, and Yii's explicit folder structure and sensible defaults make this a snap to implement.

Have you been paying attention?

It was mentioned in Chapter 1, Meet Yii that the view and controller are close cousins. So much so that $this within a view file refers to the controller class that rendered the view.

Alter the previous example by defining a public class property on MessageController, rather than a locally scoped variable, whose value is the current date and time. Then display the time in the view file by accessing this class property through $this.

In the preceding example, we explicitly fed the time to the view file from the controller by using the second argument in the render method. This second argument explicitly sets variables that are immediately available to the view file, but there is another approach we encourage you to try out for yourself.

Linking pages together

Typical web applications have more than one page within them for users to experience, and our simple application should be no exception. Let's add another page that displays a response from the World, 'Goodbye, Yii developer!', and link to this page from our Hello, World! page, and vice-versa.

Normally, each rendered HTML page within a Yii web application will correspond to a separate view (though this does not always have to be the case). So, we will create a new view and will use a separate action method to render this view. When adding a new page like this, we also need to consider whether or not to use a separate controller. As our Hello and Goodbye pages are related and very similar, there is no compelling reason to delegate the application logic to a separate controller class at the moment.

Linking to a new page

Let's have the URL for our new page be of the following form: http://yourhostname/demo/index.php?r=message/goodbye

    Sticking with Yii conventions, this decision defines the name of our action method we need in the controller as well as the name of our view. So, open up MessageController and add an actionGoodbye() method just below our actionHelloworld() action: class MessageController extends CController { { } } 3. Create an empty file in that folder, and add the single line:

    Goodbye, Yii developer!

    4. Saving and viewing again: http://yourhostname/demo/index. php?r=message/goodbye should display the goodbye message. 5. Now we need to add the links to connect the two pages. To add a link on the Hello screen to the Goodbye page, we could add an tag directly to the helloWorld view template, and hardcode the URL structure like: Goodbye! $this->render('goodbye'); ... ... public function actionGoodbye() 2. Next we have to create our view file in the /protected/views/message/ folder. This should be called goodbye.php as it should be the same as the actionID we chose.

Please do keep in mind that this is just a recommended convention. The view does not have to have the same name as the action by any means. The view filename just has to match the first argument of render().

This does work, but it tightly couples the view code implementation to a specific URL structure, which might change at some point. If the URL structure were to change, these links would become invalid.

Remember in Chapter 1, Meet Yii when we went through the blog posting application example? We used URLs that were of a different, more SEO friendly format than the Yii default format, namely: http://yourhostname/ControllerID/ActionID It is a simple matter to configure a Yii web application to use this path format as opposed to the querystring format we are using in this example. Being able to easily change the URL format can be important to web applications. As long as we avoid hardcoding them throughout our application, changing them will remain a simple matter of altering the application configuration file.

Getting a little help from Yii CHtml

Luckily, Yii comes to the rescue here. It comes with myriad helper methods that can be used in view templates. These methods exist in the static HTML helper framework class, CHtml. In this case, we want to employ the helper method link which takes in a controllerID/actionID pair, and creates the appropriate hyperlink for you based on how the URL structure is configured for the application. As all these helper methods are static, we can call them directly without the need to create an explicit instance of the CHtml class.

  1. Using this link helper, our helloWorld view becomes:
    <h1>Hello, World!</h1>
    <h3><?php echo $time; ?></h3>
    <p><?php echo CHtml::link("Goodbye",array('message/goodbye')); ?></p>
  2. Save your changes, and view the Hello, World! page at:http://yourhostname/demo/index.php?r=message/helloWorldYou should see the hyperlink, and clicking it should take you to the Goodbye page. The first parameter in the call to the link method is the text that will be displayed in the hyperlink. The second parameter is an array that holds the value for our controllerID/actionID pair. The results are displayed in the following figure:
  3. We can follow the same approach to place a reciprocal link in our goodbye view:
    <h1>Goodbye, Yii developer!</h1>
    <p><?php echo CHtml::link("Hello",array('message/helloWorld')); ?></p>
  4. Save and view the Goodbye page at the following link:http://yourhostname/demo/index.php?r=message/goodbye
    You should now see an active link back to the Hello, World! page from the Goodbye page, as shown in the following screenshot:


In this chapter, we constructed an extremely simple application to demonstrate:

  • How to install the Yii Framework
  • How to use the yiic command to bootstrap the creation of a new Yii application
  • How to use the yiic command to create a new controller within the application
  • How Yii turns incoming requests into calls to your code
  • How to create dynamic content within a controller and have it accessible to the view files for display to the browser
  • How to link internal application pages together

We have demonstrated ways to link web pages together in our simple application. One approach added an HTML tag directly to the view file and hardcoded the URL structure. The other (preferred approach) made use of Yii's CHtml helper class to help construct the URLs based on controllerID/actionID pairs, so that the resulting format will always conform to the application configuration. This way, we can easily alter the URL format throughout the application without having to go back and change every view file that happens to have internal links.

Our simple Hello, World! application really reaps the benefits of Yii's convention over configuration philosophy. By applying certain default behavior and following the recommended conventions, the building of this simple application, (and our entire request routing process) just fell together in an easy and convenient way.

While this incredibly simple application has provided concrete examples to help us better understand using the Yii Framework, it is far too simplistic to demonstrate Yii's ability to ease the building of our real-world applications. In order to demonstrate this, we need to build a real-world web application (and we will do just that). In the next chapter, we will introduce you to the project task and issue tracking application that we will be building throughout the remainder of this book.

评论 X

      Copyright 2011-2014. YiiBook.com