Book Image

Yii2 By Example

By : Fabrizio Caldarelli
Book Image

Yii2 By Example

By: Fabrizio Caldarelli

Overview of this book

Yii is a high-performance PHP framework best for developing Web 2.0 applications. It provides fast, secure, and professional features to create robust projects, however, this rapid development requires the ability to organize common tasks together to build a complete application. It's all too easy to get confused; this is where this book comes in. This book contains a series of practical project examples for developers starting from scratch. Each section contains the most relevant theories for every topic as you walk through developing each project, focusing on key aspects that commonly confuse users. The book starts with all the framework’s basic concepts, such as controllers and views, to introduce you to Yii and creating your first application, a simple news reader. You will be learn to configure URL rules to make a pretty URL, essential for search engine optimization. Next, you will walk through Model and ActiveRecord, key concepts in database interaction. The second application you will develop is a reservation system that allows you to manage rooms, customers, and reservations. For this, you will use database connection through SQL and ActiveRecord. More complex than the first one, this application will introduce you to the advanced template of Yii 2, splitting the app into two parts: a frontend for all visitors and a backend for the admin. Finally, you will move on to the last two applications: one that allows connections from remote clients, through RESTful components of Yii 2, and another that creates and organizes automatic tasks using the console application structure of Yii 2.
Table of Contents (20 chapters)
Yii2 By Example
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Naming convention


In order to allow auto-loading, Yii2 uses a simple standard to set names.

Routes that refer respectively to module, controller, and the action requested take the following format:

ModuleID/ControllerID/ActionID

We will look at each element in detail as follows:

  • The ModuleID is optional, so often the format is ControllerID/ActionID

  • The ModuleID must be specified in the module's configuration property, under the same name

  • The ControllerID and ActionID should contain only English characters in lowercase, digits, underscores, dashes, and forward slashes

An example of route is http://hostname/index.php?r=site/index, where site is the ControllerID and index is the ActionID.

Starting from ControllerID, it is very easy to create the Controller class name. Just turn into uppercase the first letter of each word separated by dashes, then remove dashes and append the suffix Controller. If ControllerID contains slashes, just apply the rules to the part after the last slash in the ID. This is possible because controllers can be collected in subfolders, starting from app\controllers.

The following are some examples:

  • Shop points to app\controllers\ShopController

  • Preferred number points to app\controllers\PreferredNumberController

  • Admin/users account points to app\controllers\admin\UsersAccountController

Routes are passed to entry script basic/web/index.php through the r parameter.

Note

The default page http://hostname/basic/web/index.php is equivalent to http://hostname/basic/web/index.php?r=site/index.

Configuring the debug toolbar

It is important to have a rich collection of tools to make development easier in displaying some useful information about requests and responses.

For this purpose, Yii2 provides a toolbar that displays several types of info.

A common way to activate the debug toolbar is to set in config/web.php:

'bootstrap' => ['debug'],
'modules' => [
  'debug' => 'yii\debug\Module',
]

Now you can set the following values:

  • debug to bootstrap config node

  • debug to modules config node, using the Module class under yii\debug\

The default installation of the Yii2 basic template already enables the debug toolbar, as we can see at the bottom of the config/web.php configuration file. The Gii module is also enabled as well, but we will work with it later.

if (YII_ENV_DEV) {
    // configuration adjustments for 'dev' environment
    $config['bootstrap'][] = 'debug';
    $config['modules']['debug'] = 'yii\debug\Module';
    $config['bootstrap'][] = 'gii';
    $config['modules']['gii'] = 'yii\gii\Module';
}

This config entry is only valid in the YII_ENV_DEV mode. So, we must check whether the web/index.php YII_ENV variable has the dev value (as shown in the default installation).

Debug toolbar closed

If we try to reload the web page at basic/web/index.php after these checks, we should see the following screenshot:

Debug toolbar opened

The right arrow reports that the debug toolbar is active but closed. If we click on it, the complete toolbar will open. Now, click on any item, the debug panel will be displayed.

By default, the debug toolbar can be used only in localhost. However, if we are using Yii2 in the remote hosting environment, we set the allowedIPs property of the debug module.

$config['modules']['debug'] = [
    'class' => 'yii\debug\Module',
    'allowedIPs' => [ '127.0.0.1', '::1']
];

In allowedIPs there is only localhost (in the IPv4 and IPv6 forms). We need to put our Internet connection and IP source address here, which can be easily found using any my IP service on the Internet, such as http://www.whatismyip.com/.

If our IP source is, for example, 1.2.3.4, we must add this entry to allowedIPs, in this way:

$config['modules']['debug'] = [
    'class' => 'yii\debug\Module',
    'allowedIPs' => [ '127.0.0.1', '::1', '1.2.3.4']
];

Remember that if we do not have an Internet connection with a static IP, this IP might change. So we need to check whether allowedIPs contains our current IP.

You could also use an asterisk * to allow all IP addresses, so you do not have to deal with dynamic IP issues. If you do this, you need to remember to remove the asterisk before deployment. Finally, at the bottom of our current configuration config/web.php, you will see the following code:

if (YII_ENV_DEV) {
    // configuration adjustments for 'dev' environment
    $config['bootstrap'][] = 'debug';
    $config['modules']['debug'] = [
        'class' => 'yii\debug\Module',
            'allowedIPs' => [ '127.0.0.1', '::1', '1.2.3.4']
    ];
    $config['bootstrap'][] = 'gii';
    $config['modules']['gii'] = 'yii\gii\Module';
}

Let's return to the basic/web/index.php webpage and take a look at the debug info panel.

The debug information is distributed in the menu:

  • Configuration: This is the installed PHP version and configuration and also the installed Yii2 framework version.

  • Request: This is the info about the request just sent, displaying parameters of the request, headers of the request and other useful data as response and session data.

  • Logs: This involves the actions performed by Yii2 during the execution. There are additional filters in this section to select the types of logs to be displayed.

  • Performance Profiling: This includes info about timing and duration of process.

  • Database: This includes info about all database query occurred; we can filter for type of query to locate a specific query.

It is possible to filter all data using internal grid filter or to filter for all, latest or selecting among the last 10 rows of the log on top of the content pane.

Using the logger

In the Yii2 application, the debug info is stored using the log component. We can use this tool both in the development and production environment, but for reasons of performance and security in production, we should log only the important messages.

The default configuration file of the Yii2 basic template provides log entry in the components property of config/web.php:

'log' => [
  'traceLevel' => YII_DEBUG ? 3 : 0,
      'targets' => [
      [
             'class' => 'yii\log\FileTarget',
             'levels' => ['error', 'warning'],
      ],
    ],
],

Example – Hello world from scratch with the Yii basic template and bootstrap template

It is now time to code our first project using Yii2.

If we have not installed Yii2 yet, we will to do it now using Composer as follows:

  1. Open Command Prompt to the web server.

  2. Go to the document root of the web server (/var/www in a Linux machine).

  3. Launch these commands (as described in the Installing Yii with Composer section):

    curl -s http://getcomposer.org/installer | php
    php composer.phar global require "fxp/composer-asset-plugin:1.0.0"
    php composer.phar create-project --prefer-dist yiisoft/yii2-app-basic basic
    

Now, we need a fresh installation of Yii2 in the basic folder of the web server document root. Point the browser to http:/hostname/basic/web and we should see Yii2's congratulations page:

An example of the Hello world page

We will create our first action to display a memorable hello world on the screen.

We know from the Application properties section, in the defaultRoute entry, that the SiteController controller will be called when no route is specified in request.

So, we enter basic/controllers and open SiteController.php, which is the default controller.

In the SiteController class definition, we add a new method at the top, called actionHelloWorld, without parameters.

public function actionHelloWorld()
{
    echo 'hello world'
}

Let's save the file and point to http://hostname/basic/web/index.php?r=site/hello-world.

You should see a blank page with hello world.

Note

Pay attention when using the name route convention. Uppercase letters are translated to lowercase and dashes.

This is fantastic, but now we just want to put hello world within the page template.

We must now create a view with the content of response hello world!. In order to do this, we need to create a file named helloWorld.php as the name of the action under views/site. The naming convention need not necessarily be the same here because the view file is not automatically called from the framework.

This file only contains the hello world text.

We update SiteController with the following code:

public function actionHelloWorld()
{
    return $this->render('helloWorld');
}

In the actionHelloWorld() method, $this refers to the SiteController's instance, and render() will insert the views/helloWorld.php file content in the main content layout page.

The extension of the view file, .php, is automatically added from the framework to view the name parameter passed to the render method.

What if we want to pass a parameter, such as name, to actionHelloWorld()? Formally, we need to add just one parameter to actionHelloWorld() in SiteController as follows:

public function actionHelloWorld($nameToDisplay)
{
    return $this->render('helloWorld',
  [ 'nameToDisplay' => $nameToDisplay ]
    );
}

Then, under view/site/helloWorld.php add the following code:

Hello World <?php echo $nameToDisplay ?>

With the update of actionHelloWorld(), we will pass as a second parameter, an array of variables, that will be visible and used in View.

When we use parameters in the action function, we must remember that they will be mandatory and we must respect the order when passing it to the request.

To avoid this obligation, we can use the old method, parsing parameters into the function:

public function actionHelloWorld()
{
    $nameToDisplay = Yii::$app->request->get('nameToDisplay');
    // Equivalent to
// $nameToDisplay = isset($_GET['nameToDisplay'])?$_GET['nameToDisplay']:null;

    return $this->render('helloWorld',
    [ 'nameToDisplay' => $nameToDisplay ]
    );
}

With this solution, we can decide whether to pass the nameToDisplay parameter to request. The default value of the nameToDisplay parameter will be null, but we can decide to assign a different value.

The following is a URL example passing the nameToDisplay parameter Foo:

http://hostname/basic/web/index.php?r=site/hello-world&nameToDisplay=Foo