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

Arrow left icon
Profile Icon Caldarelli
Arrow right icon
$19.99 per month
Full star icon Full star icon Full star icon Full star icon Empty star icon 4 (9 Ratings)
Paperback Sep 2015 344 pages 1st Edition
eBook
$9.99 $39.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.99p/m
Arrow left icon
Profile Icon Caldarelli
Arrow right icon
$19.99 per month
Full star icon Full star icon Full star icon Full star icon Empty star icon 4 (9 Ratings)
Paperback Sep 2015 344 pages 1st Edition
eBook
$9.99 $39.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.99p/m
eBook
$9.99 $39.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
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 : 9781785287411
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

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 By Example
$48.99
Mastering Yii
$54.99
Yii2 Application Development Cookbook
$54.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 included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.