• Translate

7/12/2017

Getting Started tutorial Web Application Development with Yii2 (Part 2): Controller

Tutorial PHP | Tutorial Web Design |

Advertisement

Getting Started tutorial Web Application Development with Yii2 (Part 2): Controller
Maybe for you who are familiar with using web framework, must have been familiar with MVC architecture. Where C in MVC is the controller. A controller is a code that will process requests coming from a specific URL. Controller is also tasked to perform the process of retrieving data from either the database or other resources and then display it into a response that is usually a HTML page.

According to Yii2's official documentation, the controller is a class derived from the yii\base\Controller which is responsible for processing requests and generating a response. Response can be text/html, application/json, application/pdf, and others. Yii2 has a number of variations in using the controller*. Let's see one by one.

Create a new controller

Creating a controller in Yii2 is pretty easy. You just create a file in the folder hello-yii/controllers by following a number of rules that apply so that the file can be recognized as a controller*. The basic rules are as follows :
  • Certainly the file extension should be .php
  • The file name must begin with a capital letter and end with the Controller. Eg: LoremController, StudentController, LecturerController, FlightController, HotelController, and more
  • The file name must begin with a capital letter and end with the Controller. Eg: LoremController, StudentController, LecturerController, FlightController, HotelController, and more
  • The file name must be the class name of the controller you created. When not in use there will be error not found.
Now try generating the following code into a file named HelloController.php
<?php

namespace app\controllers;

use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;

class HelloController extends Controller
{

    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
        ];
    }

    public function actionIndex()
    {
        echo "Hello World";
    }

    public function actionPosts($id=0, $category="all")
    {
        echo "Sedang menampilkan postingan dengan id: ".$id;
    }

    public function actionPostComments($id)
    {
        echo "Sedang menampilkan komentar dari postingan dengan id: ".$id;
    }

    public function actionUserPosts($user_id, $bulan, $tahun)
    {
        echo "Sedang menampilkan daftar postingan dari user dengan id ".$user_id." dengan arsip ".$bulan." / ".

$tahun;
    }
Source code above is a general structure of a controller. A class controller will extend a class of Yii2 that is the Controller class derived from the yii\web module. Then in the class there are various methods that are public which will be accessible from the web browser through a specific URL. In the source code above, you can find a code that is namespace. The namespace keyword is a marker that the file resides in a virtual path ie app\controllers. The app path is from the Yii2 app you wrote, while the controllers are the path of the controllers folder that stores the HelloController.php file. The use of the namespace is that the file can be imported from a class within the same namespace*.

Then there is the keyword use, more or less the same function as include() only this is a feature that is more modler than include. Keyword use is used to use a class that is already registered in namsepace. Now let's examine the function that is in HelloController:
  • actions(), is a standalone function that will issue a special action handled by Yii2. In the above source code, Yii2 will display an error page in case of an error
  • actionIndex(), will process requests from URLs such as http://hostname/web/index.php?r=hello/ or http://hostname/web/index.php?r=hello/index
  • actionPosts($id,$category) will process requests from URLs like http://hostname/web/index.php?r=hello/posts&id=1&category=programming, http://hostname/web/index.php?r=hello/posts, or http://hostname/web/index.php?r=hello/posts&id=10. actionPosts() has an id and category parameter that is not mandatory given the default value if it does not include both parameters
  • actionPostsComments($id) will process requests from URLs like http://hostname/web/index.php?r=hello/post-comments&id=10. The action has a mandatory parameter named id.
  • actionUserPosts($user_id,$month,$year), will process requests from URLs like http://hostname/web/index.php?r=hello/users-posts?user_id=10&month=5&year=2010. The action has three mandatory parameters that must be filled, if not filled will cause Bad Request error. 
From the above explanation can be concluded several things :
  • Parameter r is the name of the action directed to a controller with the first segment is the name of the controller and the second segment is the action name (r=controller/action)
  • A parameter other than r whose name is the same as the parameter in the action in the Controller class is the parameter that will be processed first by the action. When given the default value will not cause Bad Request error. Meanwhile, if not given the default value then it should be filled and included when requesting the action
  • Each method name must be prefixed with the action word to be recognized when accessing its URL
  • When the action name contains two words like actionPostsComments and actionUserPosts it will be separated by dash to post-comments and user-posts. Of course if you write it in camel case format. 

Create a folder inside the controller

If at any time you want to group controller files in a folder, Yii2 can already facilitate that. Now let's create a folder with the media name inside the controllers folder. Then create a file named AudioController.php inside the controllers/media folder.

Now please make the following source code in AudioController.php file :
<?php

namespace app\controllers\media;

use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;

class AudioController extends Controller
{

    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
        ];
    }

    public function actionIndex($id=null)
    {
        echo "Sedang menampilkan daftar file audio yang sudah diupload ".$id;
    }

    public function actionCreate()
    {
        echo "Disini akan muncul form tambah audio";
    }
}
Now create a file named PhotoController.php inside the controllers/media folder and create the source code below :
<?php

namespace app\controllers\media;

use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;

class PhotoController extends Controller
{

    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
        ];
    }

    public function actionIndex($id=null)
    {
        echo "Sedang menampilkan daftar foto yang sudah diupload ".$id;
    }

    public function actionCreate()
    {
        echo "Disini akan muncul form tambah foto";
    }
}
Now create a file named VideoController.php inside the controllers/media folder and create the source code below:
<?php

namespace app\controllers\media;

use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;

class VideoController extends Controller
{

    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
        ];
    }

    public function actionIndex($id=null)
    {
        echo "Sedang menampilkan daftar video yang sudah diupload ".$id;
    }

    public function actionCreate()
    {
        echo "Disini akan muncul form tambah video";
    }
}
Now you can access all three controllers with URLs like the following:
  • http://hostname/web/index.php?r=media/audio
  • http://hostname/web/index.php?r=media/audio&id=10
  • http://hostname/web/index.php?r=media/audio/create
  • http://hostname/web/index.php?r=media/video
  • http://hostname/web/index.php?r=media/video&id=10
  • http://hostname/web/index.php?r=media/video/create
  • http://hostname/web/index.php?r=media/photo
  • http://hostname/web/index.php?r=media/photo&id=10
  • http://hostname/web/index.php?r=media/photo/create
Interesting right? That's how Yii2 works in handling requests from a URL. Let's move on to the other side.

Specifies the default route

Inside the config folder there are several configuration files for params, db, console, and web. You can add a default route so that when opening a root URL it can display the controller you specify.

Please add the following configuration to the $config array just below the configuration with the key id :
$config = [
    'id' => 'basic',
    'defaultRoute' => 'hello',
    ....
    ];

Using redirect()

You can also use the built-in redirect() method of the Controller class. The method is used to redirect the page from your current page to another specified page: 
<?php

namespace app\controllers;

use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;

class HelloController extends Controller
{

    ...........................................................


    public function actionTestRedirect()
    {
        echo "Halaman ini akan diredirect ini dalam 5 detik...";
        sleep(5);
        return $this->redirect('/hello-yii/web/index.php');
    }
}

Arrange the map controller

You can also add a controller map that directs the controller to a URL you specify yourself. You can add a controller folder inside $config in the config/web.php file. In order not to confuse placement, please add controllerMap in after id
$config = [
    'id' => 'basic',
    'controllerMap' => [
        // declares "account" controller using a class name
        'demo' => 'app\controllers\HelloController',
    ],

    ... ... ...

    ];

Enable pretty url

You can also enable the pretty URL so that the URL is converted into a segmented form rather than a query string. You can add urlManager inside component parameters in $config located in config/web.php file. To avoid confusion please add urlManager at the very beginning of component parameters:
$config = [
    'id' => 'basic',

    ...

    'components => [
        'urlManager' => [
            'enablePrettyUrl' => true,
            'showScriptName' => true,
            'enableStrictParsing' => false,
            'rules' => [],
        ],

        ...

    ],
];

Closing

Now you are familiar with some techniques in using the controller in Yii2. You can also set the URL to be a pretty url or conventional version. You can also map a controller into a URL that you define yourself through the controller map. In general, Yii2 is already able to accommodate your need to define the controller under various conditions. 

Cooperation with (rfs/yiiframework)

Disqus
Blogger
Comment
How to style text in Disqus comments Top Disqus Commentators
  • To write a bold letter please use <strong></strong> or <b></b>.
  • To write a italic letter please use <em></em> or <i></i>.
  • To write a underline letter please use <u></u>.
  • To write a strikethrought letter please use <strike></strike>.
  • To write HTML code, please use <code></code> or <pre></pre> or <pre><code></code></pre>, and please parse the code in the parser box below.
Show Parser Box

No comments Add Comment

Comments not appropriate topic will sign SPAM.