Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Yii2 By Example
Yii2 By Example

Yii2 By Example: Develop complete web applications from scratch through practical examples and tips for beginners and more advanced users

eBook
$9.99 $39.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Table of content icon View table of contents Preview book icon Preview Book

Yii2 By Example

Chapter 1. Starting with Yii2

Yii2 is a complete rewrite of the first version of one of the most famous PHP frameworks. It is a well-documented framework with a very active community.

Officially, we can find three types of support: a guide, for a complete navigation through framework topics at http://www.yiiframework.com/doc-2.0/guide-index.html, a reference to explore all classes that compose the framework at http://www.yiiframework.com/doc-2.0/index.html, and finally forum support at http://www.yiiframework.com/forum/.

In this chapter, we will go through the following:

  • Requirements and tools
  • Installing Yii2 with Composer
  • Application structure
  • Application properties
    • Common application components
    • Handling application events
    • Pattern MVC in Yii2
  • Naming convention
    • Configuring debug toolbar
    • Using logger
    • Example – hello world from scratch with the Yii basic template and bootstrap template

Requirements and tools

The basic requirements for Yii2 are a web server (local or remote) and PHP v.5.4 (or newer). It is recommended to have a shell (or command line) access to the machine (local or remote) where we store the code, as there are scripts that it will be very beneficial to use in the development of complex applications. We can also develop the application locally and upload it to the web server when we wish to test it.

For remote hosting, there are multiple options. We can use a simple web hosting service (with PHP v.5.4 support) or we can opt for virtual or dedicated server hosting. Keep in mind that with the former option, if the server doesn't meet the PHP requirements, it can be difficult to change whatever is wrong.

Yii2 has a script, requirements.php, which checks whether our hosting meets the requirements to run Yii2 application.

Installing Yii2 with Composer

Composer is a tool for dependency management in PHP. Yii2 uses it to install itself and other vendors' modules (for example, bootstrap).

It is also possible to install Yii2 in the old way, by downloading the complete package and transferring it to the host, local or remote, where the framework will be installed. However, Composer will give us many benefits, like the ability to easily update the framework and ensure that all package dependencies are satisfied. Composer is de facto the new way to install and maintain projects, so I recommend using it from the start. If you are unsure about using Composer, it's worth mentioning that most users will need to learn two or three commands at most, so it's not a steep learning curve.

Yii2 has two available templates to start with: basic and advanced. We will start with the basic template, but we will also see in the next chapters how to use advanced templates.

So, let's look at how to install Yii2 with Composer. We need to access the folder through the console, where the web server's httpdocs point to and launch these commands:

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

These commands are useful if we are in the Linux or Mac environment. On Windows, you need to download Composer-Setup.exe from Composer's official website and run it.

The first command gets the http://getcomposer.org/installer URL and passes it to PHP to create the composer.phar file.

The second command installs the Composer asset plugin, which allows us to manage bower and npm package dependencies through Composer.

The third and final command installs Yii2 in a directory named basic. If you want, you can choose a different directory name.

Note

During the installation, Composer may ask for our GitHub login credentials and this is normal because Composer needs to get enough API rate limit to retrieve the dependent package information from GitHub. If you don't have a GitHub account, this is the right moment to create a new one!

If we are using Windows, we need to download it from https://getcomposer.org and run it. The last two commands will be the same.

We have installed Yii2!

To test it, point to http://hostname/basic/web and we should see the My Yii Application page.

Application structure

Yii2's application structure is very clear, precise, and redundant (for advanced applications).

The contents of the basic folder should be as follows:

Folder names

Description

assets

This includes the files (.js and .css) referenced in the web page and dependencies of the app.

commands

This includes the controllers used from the command line.

config

This includes the controllers used from web.

mail

This is the mail layout repository.

models

This includes the models used in the whole application.

runtime

This is used from Yii2 to store runtime data as logs.

tests

This includes all the test's repositories (unit, functional, fixtures, and so on).

vendor

This includes the third-party module repositories managed by Composer.

views

This contains PHP files, divided into folders that refer to controller names, used to render the main content of the page template. It is mainly called from the controller's actions to render the display output. A folder named layout contains the page template's PHP files.

web

This is the entry point from web

Open web/index.php to view content:

<?php
// comment out the following two lines when deployed to production
defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'dev');

require(__DIR__ . '/../vendor/autoload.php');
require(__DIR__ . '/../vendor/yiisoft/yii2/Yii.php');

$config = require(__DIR__ . '/../config/web.php');

(new yii\web\Application($config))->run();

Here, the first two constant definitions are very important.

YII_DEBUG defines whether you are in debug mode or not. If we set this, we will have more log information and will see the detail error call stack.

YII_ENV defines the environment mode we are working in, and its default value is prod. The available values are test, dev, and prod. These values are used in configuration files to define, for example, a different DB connection (local database different from remote database) or other values, always in configuration files.

Since we are at the start of our project, it is recommended to set YII_DEBUG to true, in order to have more detailed information in case we make a mistake in our code, instead of the unhelpful, blank.

The following table contains a list of all Yii2's objects:

Objects

Description

Models, Views, and Controllers

These are the common objects to apply the MVC pattern to:

  • Models are data representation and manipulation, usually from the database
  • Views are used to present data to the end user
  • Controllers are objects that process requests and generate responses

Components

These are objects that contain logic. The user can write his own components to create reusable functionalities.

For example, a component could be a currency converter object, which can be used at many instances in our application.

Application Components

They are singletons that can be called at any point in the app. Singleton means an object instanced just one time in the entire application (so the object will always be the same).

The difference between Application Components and Components is that the first can have just one instance in the whole application.

Widgets

These view reusable objects, containing both logic and rendering code. A widget could be, for example, a box displaying today's weather info.

Filters

These are objects that run before or after the execution of Controller actions. A filter can be used to change the format response output of the page, for example, from HTML to JSON.

Modules

This contains all the objects of an app, such as Models, Views, Controller, Components, and so on; we can consider them as subapp, containing reusable sections (for example, user management).

Extensions

Extensions are modules packaged, that we can easily manage using Composer.

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.

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
    Naming convention

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).

Configuring the debug toolbar

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:

Configuring the debug toolbar

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:

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

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

Summary

In this chapter, we looked at a basic understanding of the Yii2 framework, starting from requirements to explain the main features. Then we used debugging and logging tools to trace our code and were able to find errors. Finally, we wrote our first project based on the basic template.

Next, you will learn how to create our controllers and views, to create custom interaction with frontend users.

Left arrow icon Right arrow icon

Key benefits

  • Improve your programming experience and become a full stack developer
  • Master real-life web applications, and create and manage four different projects
  • Step-by-step guidance to develop real-world web applications smoothly

Description

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.

Who is this book for?

This book is for anyone who wants to discover and explore Yii Framework. Basic programming experience with PHP and object oriented programming is assumed.

What you will learn

  • Understand basic concepts, along with the installation and customization of Yii
  • Discover models, controllers, and views—concepts applied in a web context—and how they are employed in Yii
  • Use ActiveRecord to manipulate a database
  • Add access control to your web application through authentication and authorization
  • Install and customize an advanced template for multiple applications in the same project
  • Create a RESTful Web Service to allow remote access to data
  • Develop a console application to launch a command in the console as an automated task (cron job)
  • Make code reusable through widgets and components and localize text messages to make a multilanguage web app
Estimated delivery fee Deliver to Thailand

Standard delivery 10 - 13 business days

$8.95

Premium delivery 5 - 8 business days

$45.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Sep 29, 2015
Length: 344 pages
Edition : 1st
Language : English
ISBN-13 : 9781785287411
Tools :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to Thailand

Standard delivery 10 - 13 business days

$8.95

Premium delivery 5 - 8 business days

$45.95
(Includes tracking information)

Product Details

Publication date : Sep 29, 2015
Length: 344 pages
Edition : 1st
Language : English
ISBN-13 : 9781785287411
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 158.97
Yii2 Application Development Cookbook
$54.99
Mastering Yii
$54.99
Yii2 By Example
$48.99
Total $ 158.97 Stars icon
Banner background image

Table of Contents

14 Chapters
1. Starting with Yii2 Chevron down icon Chevron up icon
2. Creating a Simple News Reader Chevron down icon Chevron up icon
3. Making Pretty URLs Chevron down icon Chevron up icon
4. Creating a Room through Forms Chevron down icon Chevron up icon
5. Developing a Reservation System Chevron down icon Chevron up icon
6. Using a Grid for Data and Relations Chevron down icon Chevron up icon
7. Working on the User Interface Chevron down icon Chevron up icon
8. Log in to the App Chevron down icon Chevron up icon
9. Frontend to Display Rooms to Everyone Chevron down icon Chevron up icon
10. Localize the App Chevron down icon Chevron up icon
11. Creating an API for Use in a Mobile App Chevron down icon Chevron up icon
12. Create a Console Application to Automate the Periodic Task Chevron down icon Chevron up icon
13. Final Refactoring Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
(9 Ratings)
5 star 55.6%
4 star 22.2%
3 star 0%
2 star 11.1%
1 star 11.1%
Filter icon Filter
Top Reviews

Filter reviews by




Davidc316 Apr 17, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This is a great book for anyone who wants to learn about how to use the Yii2 framework. From the get-go, it starts by dealing with many of the questions that you might have been afraid to ask on the Yii forum. Questions like;* How do layouts work?* How can you switch between different types of page template?* How do you deal with re-usable snippets of HTML code?I think, when you're teaching Yii2 there's a temptation to go straight into the Gii and to show people how to quickly generate code with a few clicks. It's a great trick and it is bound to impress a few people. However, I think that kind of strategy is a flaw and thankfully the author doesn't fall down that trap. Instead, he takes the reader through all of the basics first, then - once you have a solid foundation - he'll move you onto the Gii. This is surely the best way of learning Yii2.All of the examples that the author walks you through are practical and clearly explained. Of course, later on it also goes beyond just ordinary webpage construction and goes into more advanced material like creating console applications and how to build restful APIs. Like any book, I'm sure it's not perfect. However, I think it is as good as any person could reasonably expect from a book on this kind of subject matter.It's a definite thumbs up from me.
Amazon Verified review Amazon
Mr Clean Apr 18, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
All is well and good.
Amazon Verified review Amazon
Kindle Customer Jul 21, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Excellent book, I can't recommend it enough for anyone wanting to learn this framework!
Amazon Verified review Amazon
Tristan Bendixen Oct 30, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I was one of the technical reviewers on this book, and have thus read the book thoroughly from start to end.The book requires a working knowledge of PHP and associated technologies, but as long as you have that, you are bound to find the book useful. Whether you're just starting out with Yii2 or you've been playing around with it a bit, Yii2 By Example contains a lot of useful information.While a user with some experience in Yii2 development may not benefit a lot from the first few sections, in which everything is set up and explained, the book quickly becomes useful as it dives deeper, while still explaining things in an easy-to-understand manner.Of particular interest to those who are interested in developing more advanced Yii2 applications are the chapters that pertains to the advanced application template, such as the separation of frontend and backend with a common layer for models and configs, the development of a REST API, and of course creation of console commands that can be used in cronjobs or for maintenance tasks.One of the things I love about the 'By Example' series of books from Packt Publishing, is the way a lot of subjects are covered from multiple angles when possible. A good example of this, in Yii2 By Example, would be the access control sections, where multiple methods are shown and explained.
Amazon Verified review Amazon
Alvaro Oct 20, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Nice and needed approach to move from Yii to Yii2 and also to start from scratch with this awesome framework.It covers everything I need to trace the correct path on building strong web apps (including the creation of an api to be connected from foreign services or mobile apps) and gives hints on searching for further functionalities.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela