Tuesday, 26 March 2019

Yii first controller and URLs

This is partly based on the documentation found at https://www.yiiframework.com/doc/guide/2.0/en/start-hello
Within the controllers directory I have a file called SiteController.php. I'll explain a few things about it.

site is the default route for Yii applications and therefore SiteController.php would be (by default) the first controller a user interaction would access. So if I access my application through the URL http://localhost/test/yii-apps/basic/web/ then (by default) the SiteController would be called, and (by deafult) the actionIndex method would be called within that controller.

actionIndex renders the view views/site/index.php within the default layout views/layouts/main.php

In order to create a controller we need to make use of the controller classes declared at the top.

The method actionSay can be called from the URL http://localhost/test/yii-apps/basic/web/index.php
?r=site%2Fsay and within this URL, the r stands for route. route's format is ControllerID/ActionID. This would render the view views/site/say.php within the default layout views/layouts/main.php showing the content 'Hello' since this is the default value of the variable message.

The %2F is the URL encoded version of /

views/site/say.php looks like this:

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

To extend this approach the URL http://localhost/test/yii-apps/basic/web/index.php?r=site%2Fsay&message=Hello+Mick would pass a string Hello+Mick to the value of the variable message and the resulting page would display the string 'Hello Mick'.

Thus SiteController.php looks like this.

<?php
namespace app\controllers;
use yii\web\Controller;
class SiteController extends Controller
{
    public function actionIndex()
    {
        return $this->render('index');
    }

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

No comments:

Post a Comment