YII First Example

After installing Yii, you can develop an application that can be accessed via URL http://hostname/basic/web/index.php orhttp://hostname/index.php depending upon your configuration.

We'll run a basic example of Hello World on Yii2.

# Step1 Declaring action in controllers

We are creating an action called example. This action will read a message parameter from the request and will display that message.

Action is always declared in the Controllers file. Here, we are not creating a new file and is declaring this action in the existing SiteController.php.

Following is the starting code in SiteController.php file.

namespace frontend\controllers; 

use Yii; 
use yii\base\InvalidParamException; 
use yii\web\BadRequestHttpException; 
use yii\web\Controller; 
use yii\filters\VerbFilter; 
use yii\filters\AccessControl; 
use common\models\LoginForm; 
use frontend\models\PasswordResetRequestForm; 
use frontend\models\ResetPasswordForm; 
use frontend\models\SignupForm; 
use frontend\models\ContactForm; 

 * Site controller 
class SiteController extends Controller 
     * @inheritdoc 

    public function actionExample($message = 'Hello') 
        return $this->render('example', ['message' => $message]); 

Look at the above code, example action is defined as a method named actionExample. Prefix action is used to differentiate action methods from non-action methods. Name after the prefix action denotes the action's ID.

Here we're taking a parameter $message, whose value is "Hello". If a request is sent with a message parameter in the URL with a different value say "Hyii", then this value will be displayed in the output. If no message parameter request is made in the URL, then "Hello" will be printed.

Function render() is called to display view file named example.php. This result will be displayed to the end user in the browser.

# Step1 Creating View file

View folder basically contains the response content which will be delivered to the user on their request. In this example, we have created a file named example.php in the view/site folder.

Following is the code of example.php file.

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

Look at the above code, the message parameter is HTML encoded before being printed to prevent from XSS attack.

# Step1 Running on Browser

Access the page with the following URL:


output is shown below.

YII Running 1

Look at the above snapshot, output displays Hello World. In the URL, we have requested for message parameter.

If we'll omit the message parameter in the URL, then our URL will be:


and our Output will be only "Hello".

YII Running 2

In the URL, we have mentioned an r parameter. This r denotes to route. It's format is ControllerID/AtionID. In this example route denotes site/example.