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
Newsletter 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
€8.99 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
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

Billing Address

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

Yii2 By Example

Chapter 2. Creating a Simple News Reader

This chapter explains how to write your first controller in order to display news items list and details, make interactions between controllers and views, and then customize the view's layout.

In this chapter, we will go through the following:

  • Creating controller and action
  • Creating a view to display the news list
  • How the controller sends the data to view
    • Example – create a controller to display the static news items list and details
  • Split the common view content into reusable views
    • Example – render partial in view
  • Creating static pages
  • Share data between views and layout
    • Example – change layout background based on the URL parameter
  • Layout with dynamic blocks
    • Example – add dynamic box to display advertising info
  • Using multiple layouts
    • Example – using different layout to create responsive and not responsive layout for the same view

Creating Controller and Action

In order to handle a request, the first thing to do is to create a new controller.

The things you must remember while creating a file controller are as follows:

  • The namespace at the top (in basic application usually app\controllers)
  • The use path for used class
  • The controller class must extend the yii\web\Controller class
  • The actions are handled from controller functions whose name starts with action and the first letter of each word is in uppercase

Let's point to basic/controllers and create a file named NewsController.php.

Then, create a class with the same name as the file and extend it from controller; finally, create an action named index to manage request for news/index:

<?php

// 1. specify namespace at the top (in basic application usually app\controllers);
namespace app\controllers;

// 2. specify 'use' path for used class;
use Yii;
use yii\web\Controller;

// 3. controller class must extend yii\web\Controller class;
// This line is equivalent...

Creating a view to display a news list

Now, we will create a simple news list in a view named itemsList. We will point to this view from NewsController, so we have to:

  • Create a news folder under basic/views, that NewsController will use as the base folder to search for the views to be rendered (according to the view names' rules explained in the previous chapter)
  • Create an itemsList.php file under basic/views/news

Now, open basic/views/news/itemsList.php, create an array with a list of data and display the output with a simple table of items:

<?php
    $newsList = [
        [ 'title' => 'First World War', 'date' => '1914-07-28' ],
        [ 'title' => 'Second World War', 'date' => '1939-09-01' ],
        [ 'title' => 'First man on the moon', 'date' => '1969-07-20' ]
    ];
?>

<table>
    <tr>
        <th>Title</th>
   ...

How the controller sends data to view

In the previous paragraph, we have seen how to display the content view. However, the view should only be responsible for displaying data, and not for manipulation. Consequently, any work on data should be done in controller action and then passed to view.

The render() method in the action of the controller has a second parameter, which is an array whose keys are names of variables, and values are the content of these variables available in view context.

Now, let's move all data manipulation of our itemsList example in controller, leaving out just the code to format the output (such as HTML).

The following is the content of the actionItemsList() controller:

public function actionItemsList()
{
  $newsList = [
    [ 'title' => 'First World War', 'date' => '1914-07-28' ],
    [ 'title' => 'Second World War', 'date' => '1939-09-01' ],
    [ 'title' =&gt...

Splitting the common view content into reusable views

Sometimes, views share the same common portion of content. In the examples made until now, we have seen that a common area for itemsList and itemDetail could be copyright data, which displays a disclaimer about copyright info.

In order to make this, we must put the common content in a separate view and call it using the renderPartial() method of controller (http://www.yiiframework.com/doc-2.0/yii-base-controller.html#renderPartial%28%29-detail). It has the same types of parameters of the render() method; the main difference between the render() and renderPartial() methods is that render() writes a view content in layout and renderPartial() writes only view contents to output.

Example – render partial in view

In this example, we create a common view for both itemsList and itemDetail about copyright data.

Create a view file named _copyright.php in views/news.

Note

Usually, in Yii2's app, a view name that starts with underscore stands...

Creating static pages

All websites contain static pages, whose content is static.

To create a static page in a common way, we need to:

  • Create a function (action) to execute action in Controller
  • Create a view for static content

Append the following action to Controller:

public function actionInfo()
{
    return $this->render('info');
}

Then, create a view in views/controller/action-name.php. This procedure is simple but too long and redundant.

Yii2 provides a quick alternative, adding static pages to the actions() method of Controller as follows:

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

With this simple declaration, we can put all static content under views/controllerName/pages.

Finally, we can point to the URL with route controller_name/page and the view parameter with the name of a view file such as http://hostname/basic/web/index.php?r=controllerName/pages&view=name_of_view.

Example...

Creating Controller and Action


In order to handle a request, the first thing to do is to create a new controller.

The things you must remember while creating a file controller are as follows:

  • The namespace at the top (in basic application usually app\controllers)

  • The use path for used class

  • The controller class must extend the yii\web\Controller class

  • The actions are handled from controller functions whose name starts with action and the first letter of each word is in uppercase

Let's point to basic/controllers and create a file named NewsController.php.

Then, create a class with the same name as the file and extend it from controller; finally, create an action named index to manage request for news/index:

<?php

// 1. specify namespace at the top (in basic application usually app\controllers);
namespace app\controllers;

// 2. specify 'use' path for used class;
use Yii;
use yii\web\Controller;

// 3. controller class must extend yii\web\Controller class;
// This line is equivalent to
// class...

Creating a view to display a news list


Now, we will create a simple news list in a view named itemsList. We will point to this view from NewsController, so we have to:

  • Create a news folder under basic/views, that NewsController will use as the base folder to search for the views to be rendered (according to the view names' rules explained in the previous chapter)

  • Create an itemsList.php file under basic/views/news

Now, open basic/views/news/itemsList.php, create an array with a list of data and display the output with a simple table of items:

<?php
    $newsList = [
        [ 'title' => 'First World War', 'date' => '1914-07-28' ],
        [ 'title' => 'Second World War', 'date' => '1939-09-01' ],
        [ 'title' => 'First man on the moon', 'date' => '1969-07-20' ]
    ];
?>

<table>
    <tr>
        <th>Title</th>
        <th>Date</th>
    </tr>
    <?php foreach($newsList as $item) { ?>
    <tr>
        <td...

How the controller sends data to view


In the previous paragraph, we have seen how to display the content view. However, the view should only be responsible for displaying data, and not for manipulation. Consequently, any work on data should be done in controller action and then passed to view.

The render() method in the action of the controller has a second parameter, which is an array whose keys are names of variables, and values are the content of these variables available in view context.

Now, let's move all data manipulation of our itemsList example in controller, leaving out just the code to format the output (such as HTML).

The following is the content of the actionItemsList() controller:

public function actionItemsList()
{
  $newsList = [
    [ 'title' => 'First World War', 'date' => '1914-07-28' ],
    [ 'title' => 'Second World War', 'date' => '1939-09-01' ],
    [ 'title' => 'First man on the moon', 'date' => '1969-07-20' ]
  ];

  return $this->render('itemsList...

Splitting the common view content into reusable views


Sometimes, views share the same common portion of content. In the examples made until now, we have seen that a common area for itemsList and itemDetail could be copyright data, which displays a disclaimer about copyright info.

In order to make this, we must put the common content in a separate view and call it using the renderPartial() method of controller (http://www.yiiframework.com/doc-2.0/yii-base-controller.html#renderPartial%28%29-detail). It has the same types of parameters of the render() method; the main difference between the render() and renderPartial() methods is that render() writes a view content in layout and renderPartial() writes only view contents to output.

Example – render partial in view

In this example, we create a common view for both itemsList and itemDetail about copyright data.

Create a view file named _copyright.php in views/news.

Note

Usually, in Yii2's app, a view name that starts with underscore stands for common...

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

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 : 9781785283673
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
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

Billing Address

Product Details

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

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.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
€189.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
€264.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 120.97
Yii2 By Example
€36.99
Mastering Yii
€41.99
Yii2 Application Development Cookbook
€41.99
Total 120.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

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.