start-hello.md 7.38 KB
Newer Older
1 2 3
Saying Hello
============

Larry Ullman committed
4 5
This section describes how to create a new "Hello" page in your application.
To achieve this goal, you will create an [action](structure-controllers.md) and 
Qiang Xue committed
6 7
a [view](structure-views.md):

Larry Ullman committed
8 9
* The application will dispatch the page request to the action
* And the action will in turn render the view that shows "Hello" to the end user
10

Larry Ullman committed
11
Through this tutorial, you will learn how:
12

Larry Ullman committed
13 14 15
* To create an [action](structure-controllers.md) to respond to requests
* To create a [view](structure-views.md) to compose the response's content
* An application dispatches requests to [actions](structure-controllers.md)
16 17


Qiang Xue committed
18
Creating an Action <a name="creating-action"></a>
19 20
------------------

Larry Ullman committed
21 22 23
For the "Hello" task, you will create a `say` [action](structure-controllers.md) that reads
a `message` parameter from the request and displays that message back to the user. If the request
does not provide a `message` parameter, the action will display the default "Hello" message.
Qiang Xue committed
24 25 26 27

> Info: [Actions](structure-controllers.md) are the objects that end users can directly refer to for
  execution. Actions are grouped by [controllers](structure-controllers.md). The execution result of
  an action is the response that an end user will receive.
28

Qiang Xue committed
29
Actions must be declared in [controllers](structure-controllers.md). For simplicity, you may
Larry Ullman committed
30 31
declare the `say` action in the existing  `SiteController`. This controller is defined
in the class file `controllers/SiteController.php`. Here is the start of the new action:
32 33

```php
34 35
<?php

Qiang Xue committed
36 37 38 39
namespace app\controllers;

use yii\web\Controller;

40 41 42 43 44 45 46 47 48 49 50 51
class SiteController extends Controller
{
    // ...existing code...

    public function actionSay($message = 'Hello')
    {
        return $this->render('say', ['message' => $message]);
    }
}
```

In the above code, the `say` action is defined as a method named `actionSay` in `SiteController`.
Qiang Xue committed
52
Yii uses the prefix `action` to differentiate action methods from non-action methods in a controller class.
Larry Ullman committed
53
The name after the `action` prefix is maps to the action's ID.
54

Larry Ullman committed
55 56
When it comes to naming your actions, you should understand how Yii treats action IDs. Action IDs are always referenced in lower case. If an action ID requires multiple words, they will be concatenated by dashes (e.g., `create-comment`). Action method names are mapped to action IDs by removing any dashes from the IDs,
  capitalizing the first letter in each word, and prefixing the resulting with `action`. For example,
Qiang Xue committed
57
  the action ID `create-comment` corresponds to the action method name `actionCreateComment`.
58

Larry Ullman committed
59 60 61
The action method takes a parameter `$message`, whose value defaults to `"Hello"` (in exatly the same way you set a default value for any function or method argument in PHP). When the application
receives a request and determines that the `say` action is responsible for handling said request, the application will
populate this parameter with the same named parameter found in the request. In other words, if the request includes a `message` paremter with a value of `"Goodbye"`, the $message variable within the action will be assigned that value.
62

Qiang Xue committed
63
Within the action method, [[yii\web\Controller::render()|render()]] is called to render
Larry Ullman committed
64 65 66
a [view](structure-views.md) file named `say`. The `message` parameter is also passed to the view
so that it can be used there. The rendering result is returned by the action method. That result will be received
by the application and displayed to the end user in the browser (as part of a complete HTML page). 
67 68


Qiang Xue committed
69
Creating a View <a name="creating-view"></a>
70 71
---------------

Larry Ullman committed
72 73
[Views](structure-views.md) are scripts you write to generate a response's content.
For the "Hello" task, you will create a `say` view that prints the `message` parameter received from the action method, and passed by the action to the view:
74 75 76 77 78 79 80 81

```php
<?php
use yii\helpers\Html;
?>
<?= Html::encode($message) ?>
```

Qiang Xue committed
82 83 84
The `say` view should be saved in the file `views/site/say.php`. When the method [[yii\web\Controller::render()|render()]]
is called in an action, it will look for a PHP file named as `views/ControllerID/ActionID/ViewName.php`.

85
Note that in the above code, the `message` parameter is [[yii\helpers\Html::encode()|HTML-encoded]]
Larry Ullman committed
86
before being printed. This is necessary as the parameter comes from an end user, making it vulnerable to
87 88 89
[cross-site scripting (XSS) attacks](http://en.wikipedia.org/wiki/Cross-site_scripting) by embedding
malicious JavaScript code in the parameter.

Larry Ullman committed
90 91 92
Naturally, you may put more content in the `say` view. The content can consist of HTML tags, plain text, and even PHP statements.
In fact, the `say` view is just a PHP script that is executed by the [[yii\web\Controller::render()|render()]] method.
The content printed by the view script will be returned to the application as the response's result. The application will in turn output this result to the end user.
93 94


Qiang Xue committed
95 96
Trying it Out <a name="trying-it-out"></a>
-------------
97 98 99 100 101 102 103

After creating the action and the view, you may access the new page by the following URL:

```
http://hostname/index.php?r=site/say&message=Hello+World
```

104 105
![Hello World](images/start-hello-world.png)

Larry Ullman committed
106 107 108 109
This URL will result in a page displaying "Hello World". The page shares the same header and footer as the other application pages. 

If you omit the `message` parameter in the URL, you would see the page display just "Hello". This is because `message` is passed as a parameter to the `actionSay()` method, and when it is omitted,
the default value of `"Hello"` will be used instead.
110

Qiang Xue committed
111 112 113
> Info: The new page shares the same header and footer as other pages because the [[yii\web\Controller::render()|render()]]
  method will automatically embed the result of the `say` view in a so-called [layout](structure-views.md) `views/layouts/main.php`.

Larry Ullman committed
114 115 116
The `r` parameter requires more explanation. It stands for [route](runtime-routing.md), a globally unique ID
that refers to an action. The route's format is `ControllerID/ActionID`. When the application receives
a request, it will check this parameter, using the `ControllerID` part to determine which controller
117
class should be instantiated to handle the request. Then, the controller will use the `ActionID` part
Larry Ullman committed
118 119
to determine which action should be instantiated to do the real work. In this example case, the route `site/say`
will be resolved to the `SiteController` controller class and the `say` action. As a result,
120 121
the `SiteController::actionSay()` method will be called to handle the request.

Qiang Xue committed
122 123
> Info: Like actions, controllers also have IDs that uniquely identify them in an application.
  Controller IDs use the same naming rules as action IDs. Controller class names are derived from
Larry Ullman committed
124 125
  controller IDs by removing dashes from the IDs, capitalizing the first letter in each word,
  and suffixing the resulting string with the word `Controller`. For example, the controller ID `post-comment` corresponds
Qiang Xue committed
126 127
  to the controller class name `PostCommentController`.

128

Qiang Xue committed
129
Summary <a name="summary"></a>
130 131
-------

Larry Ullman committed
132 133 134
In this section, you have touched the controller and view parts of the MVC design pattern.
You created an action as part of a controller to handle a specific request. And you also created a view
to compose the response's content. In this simple example, no model was involved as the only data used was the `message` parameter.
Qiang Xue committed
135

Larry Ullman committed
136
You have also learned about routes in Yii, which act as the bridge between user requests and controller actions.
137

Larry Ullman committed
138
In the next section, you will learn how to create a model, and add a new page containing an HTML form.