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

Application properties


A Yii2 application can be configured through several properties.

The properties that need to be configured in any application are listed in the following table:

Properties

Description

id

This indicates a unique ID to distinguish this application from others. It is mainly used programmatically. An example of this property is basic.

basePath

This specifies the root directory of the application. This path is the starting point for all the other types of application objects, such as models, controllers, and views. An example of this property is dirname(__DIR__).

The other common properties are listed in the following table:

Properties

Description

aliases

This indicates an alias name for path definitions. They are defined using a key/value array and they are very useful when we need to set a path as a constant that live in the whole application. We type an alias preceded by an @ character. An example of this property is '@fileupload' => 'path/to/files/uploaded'.

bootstrap

This property allows you to configure an array of components to be run during the application bootstrap process. A common usage is to load the log or profile component, gii, or any other component. Be careful not to load too many components, otherwise the response performance of your pages may degrade. An example of this property is 'log', 'gii'.

catchAll

This property captures every request and it is used in the maintenance mode of the site.

components

This property points out a list of application components that you can use in the whole application.

language

This property specifies the language used to display the content. An example of this property is 'language' => 'en'.

modules

This property points out a list of application modules that can be used in the application.

name

This property indicates the name of your app. An example of this property is 'name' => 'My App'.

params

This property specifies an array of parameters, through key/value pairs. This is a container for global params, such as the administrator's e-mail address.

timeZone

This property indicates the time zone that should be used in the application. An example of this property is 'timeZone' => 'Europe/Rome'.

charset

This property points out the charset used in the application. The default value is UTF-8.

defaultRoute

This property contains a route to be used when a request does not a specify one. This property has different default values according to the environment we are using.

For web applications, this value will be site, so that SiteController could be used to handle these requests.

For console applications, this value will be help, so that yii\console\controllers\HelpController can be used invoking its index action that will display help information.

Common application components

Here's a list of the most-used application components:

  • request: This component handles all client requests and provides methods to easily get parameters from server global variables, such as $_SERVER, $_POST, $_GET, and $_COOKIES.

    The default state has enableCookieValidation set to true, so you need to set cookieValidationKey parameter as shown in this example:

    'request' => [
    'cookieValidationKey' => 'hPpnJs7tvs0T4N2OGAY',
    ],
  • cache: This component helps you handle cache data. Yii2 defaults to the FileCache instance for the cache, but we can also configure an ApcCache, DbCache, MemCache, and so on.

    The following is a standard installation of Yii2:

    'cache' => [                     
    'class' => 'yii\caching\FileCache',
    ],
  • user: This component deals with user authentication in the app. The most important parameter is the identityClass parameter, which defines the class that contains the user's model data, in order to have a specific method to log in or log out a user from the app.

    Consider the following example:

    'user' => [
    'identityClass' => 'app\models\User',
             'enableAutoLogin' => true,
     ],
  • errorHandler: This component provides functionalities to handle uncaught errors and exceptions. It can be configured by specifying the action to run.

    Consider the following example:

    'errorHandler' => [
    'errorAction' => 'site/error',
    ],
  • mailer: This component configures mailer connection parameters to the system that will send an e-mail. Usually, it is the same machine hosting our website, so the default values are probably correct.

    Consider the following example:

    'mailer' => [
      'class' => 'yii\swiftmailer\Mailer',
      // send all mails to a file by default. You have to set
      // 'useFileTransport' to false and configure a transport
         // for the mailer to send real emails.
         'useFileTransport' => true,
    ],
  • log: This component is mainly used in the debug environment to log the app execution. We can set the debug level and destination.

    Consider the following example:

    'log' => [
               'traceLevel' => YII_DEBUG ? 3 : 0,
                'targets' => [
                    [
                        'class' => 'yii\log\FileTarget',
                        'levels' => ['error', 'warning'],
                    ],
                ],
     ],
  • db: This component handles a database connection. We can have several db configuration in our app; in this case, we can define more components with the Connection class located at yii\db\.


    Consider the following example:

    db => [
        'class' => 'yii\db\Connection',
        'dsn' => 'mysql:host=localhost;dbname=yii2basic',
        'username' => 'dbuser'',
        'password' => 'dbpassword',
        'charset' => 'utf8',
    ],

Handling application events

During its lifecycle, an application can trigger many events. These events can be declared in application configuration or programmatically. Common triggers are beforeRequest, afterRequest, beforeAction, and afterAction, but every object can have its own events.

For example, a common use of events is to set mysql db timezone.

To set the time zone to UTC in db component configuration, we must define a handler for the afterOpen event:

'db' => [
  'class' => 'yii\db\Connection',
  'dsn' => 'mysql:host=localhost;dbname=mydb',
  'username' => 'dbuser',
  'password' => 'dbpassword',
  'charset' => 'utf8',

  'on afterOpen' => function($event) {
    $event->sender->createCommand("SET time_zone = '+00:00'")->execute();
       }
  ],

An anonymous function, attached to on afterOpen event handlers, has an $event parameter, which is an instance of the yii\base\ActionEvent class. This class has a $sender object that refers to the sender of the event. In this case, $sender refers to the instance of database components (db). This property may also be null when this event is a class-level event.

The MVC pattern in Yii2

Yii2 is built according to the Model-View-Controller (MVC) design pattern.

Models, representing logic, are objects extended from \yii\base\Model, which offer many features such as attribute, attribute labels, massive assignment (to fill object attributes directly for an array), validation rules, and data exporting.

Normally, in common apps, a Model will be generated from the database, extending yii\db\ActiveRecord that implements the Active Record design pattern, with many methods to manipulate data. Yii2 provides Gii, a tool used to generate Model classes directly from the database's table structure.

Controllers, the bridge between view and model, are class instances extending from yii\base\Controller, used to process requests and generate responses.

Controllers mainly contain functions whose name starts with the action prefix that allows the framework to recognize those functions as routes, which can be requested.

Finally, we will look at views that deal with displaying data to end users that are mainly rendered in the page layout from controllers.