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

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

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

Carsten Brandt committed
11
Through this tutorial, you will learn three things:
12

Carsten Brandt committed
13 14 15
1. How to create an [action](structure-controllers.md) to respond to requests,
2. how to create a [view](structure-views.md) to compose the response's content, and
3. how an application dispatches requests to [actions](structure-controllers.md#creating-actions).
16 17


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

Carsten Brandt committed
21
For the "Hello" task, you will create a `say` [action](structure-controllers.md#creating-actions) that reads
Larry Ullman committed
22 23
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

Carsten Brandt committed
25
> Info: [Actions](structure-controllers.md#creating-actions) are the objects that end users can directly refer to for
Qiang Xue committed
26 27
  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
class SiteController extends Controller
{
    // ...existing code...

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

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

Carsten Brandt committed
55 56 57 58 59
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,
the action ID `create-comment` corresponds to the action method name `actionCreateComment`.
60

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

Qiang Xue committed
67
Within the action method, [[yii\web\Controller::render()|render()]] is called to render
Larry Ullman committed
68 69 70
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). 
71 72


Qiang Xue committed
73
Creating a View <a name="creating-view"></a>
74 75
---------------

Larry Ullman committed
76 77
[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:
78 79 80 81 82 83 84 85

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

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

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

Larry Ullman committed
94 95 96
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.
97 98


Qiang Xue committed
99 100
Trying it Out <a name="trying-it-out"></a>
-------------
101

Carsten Brandt committed
102
After creating the action and the view, you may access the new page by accessing the following URL:
103 104 105 106 107

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

108 109
![Hello World](images/start-hello-world.png)

Larry Ullman committed
110 111 112 113
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.
114

Qiang Xue committed
115
> Info: The new page shares the same header and footer as other pages because the [[yii\web\Controller::render()|render()]]
Carsten Brandt committed
116 117
  method will automatically embed the result of the `say` view in a so-called [layout](structure-views.md#layouts) which in this
  case is located at `views/layouts/main.php`.
Qiang Xue committed
118

Carsten Brandt committed
119
The `r` parameter in the above URL requires more explanation. It stands for [route](runtime-routing.md), an application wide unique ID
Larry Ullman committed
120 121
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
122
class should be instantiated to handle the request. Then, the controller will use the `ActionID` part
Larry Ullman committed
123 124
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,
125 126
the `SiteController::actionSay()` method will be called to handle the request.

Qiang Xue committed
127 128
> 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
129 130
  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
131 132
  to the controller class name `PostCommentController`.

133

Qiang Xue committed
134
Summary <a name="summary"></a>
135 136
-------

Larry Ullman committed
137 138 139
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
140

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

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