41,99 €
Discover 100 useful recipes that will bring the best out of the Yii2 framework and be on the bleeding edge of web development today
This book is for developers with good PHP5 knowledge and MVC-frameworks who have tried to develop applications using the Yii 1.x.x version. This book will very useful for all those who would like to try Yii2, or those who are afraid to move from Yii 1.x.x. to Yii2. If you have still not tried Yii2, this book is definitely for you!
Yii is a free, open source web application development framework written in PHP5 that promotes clean DRY design and encourages rapid development. It works to streamline your application development time and helps to ensure an extremely efficient, extensible, and maintainable end product. Being extremely performance optimized, Yii is a perfect choice for any size project. However, it has been built with sophisticated, enterprise applications in mind. You have full control over the configuration from head-to-toe (presentation-to-persistence) to conform to your enterprise development guidelines. It comes packaged with tools to help test and debug your application, and has clear and comprehensive documentation.
This book is a collection of Yii2 recipes. Each recipe is represented as a full and independent item, which showcases solutions from real web-applications. So you can easily reproduce them in your environment and learn Yii2 fast and without tears. All recipes are explained with step-by-step code examples and clear screenshots.
Yii2 is like a suit that looks great off the rack, but is also very easy to tailor to fit your needs. Virtually every component of the framework is extensible. This book will show how to use official extensions, extend any component, or write a new one.
This book will help you create modern web applications quickly, and make sure they perform well using examples and business logic from real life. You will deal with the Yii command line, migrations, and assets. You will learn about role-based access, security, and deployment. We'll show you how to easily get started, configure your environment, and be ready to write web applications efficiently and quickly.
The chapters of this book are independent and offer a practical approach to Yii development. You can start reading from the chapter you need most, be it Ajax and jQuery, RESTful Web Services, Database, Active Record, or Official Extensions
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 388
Veröffentlichungsjahr: 2016
Copyright © 2016 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: August 2011
Second edition: April 2013
Third edition: October 2016
Production reference: 1261016
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78528-176-1
www.packtpub.com
Authors
Andrew Bogdanov
Dmitry Eliseev
Alexander Makarov
Reviewer
Maurizio Domba Cerin
Commissioning Editor
Ashwin Nair
Acquisition Editors
Vivek Anantharaman
James Jones
Aaron Lazar
Content Development Editor
Sanjeet Rao
Technical Editors
Bhagyashree Rai
Nidhisha Shetty
Copy Editor
Tom Jacob
Project Coordinator
Judie Jose
Proofreader
Safis Editing
Indexer
Pratik Shirodkar
Graphics
Kirk D'Penha
Production Coordinator
Deepika Naik
Cover Work
Deepika Naik
Andrew Bogdanov is a seasoned web developer from Yekaterinburg, Russia with more than six years of experience in industrial development. Since 2010 he has been interested in Yii and MVC frameworks. He has taken part in projects written in Yii such as a work aggregator for a UK company, high-load projects, real-estate projects, and development of private projects for the government.
He has worked on various CMS and frameworks using PHP and MySQL, which includes Yii, Kohana, Symphony, Joomla, WordPress, CakePHP, and so on. Also, having good hands in integrating third-party APIs such as Payment gateways (Paypal, Facebook, Twitter, and LinkedIn), he is very good in slicing and frontend. So he can provide full information about Yii framework.
He is also well-versed in PHP/MYSQL, Yii 1.x.x, Yii 2.x.x, Ajax, JQuery, MVC frameworks, Python, LAMP, HTML/CSS, Mercurial, Git, AngularJs, and adaptive markup. You can also visit his blog http://jehkinen.com.
In his free time he likes to visit and talk with new people and discuss web development problems. He is currently working with professionals http://2amigos.us.
Dmitry Eliseev has been a web developer since 2008 and specializes in server-side programming on PHP and PHP frameworks.
Since 2012 he has authored his personal blog, http://elisdn.ru, about web development in general and about the Yii Framework particularly. His blog became a well-known resource in the Russian Yii community. He is an active member of a Russian-language forum http://yiiframework.ru.
Dmitry is interested in developmental best practices, software architectures, object-oriented programming, and other approaches.
He is an author and a presenter of practical courses about principles and best practices of object oriented programming and the use of version control systems. And also he is an author of webinars, the Yii2 Framework, and common developmental subjects. He practices teaching and counseling by development on frameworks and using of principles of software design and improvements of common code quality. This is his first book.
Alexander Makarov is an experienced engineer from Russia and has been a Yii framework core team member since 2010. Before joining the Yii core team, he participated in the CodeIgniter community growth in Russia. In 2009, he finished the Russian translation of the framework documentation and created the Russian community website. In 2012, he released the Russian version of the book along with Russian community members. In the same year, he was the technical reviewer for three more books:
In his free time, Alexander writes technical blog at http://rmcreative.ru/, speaks at conferences, and enjoys movies, music, traveling, photography, and languages. He currently resides in Voronezh, Russia with his beloved wife and daughter.
Maurizio Domba Cerin is a frontend and backend web developer with over 24 years of professional experience in computer programming and 13 years in web development. He is an active member of the Yii community. At the moment he is developing intranet web applications for an export-import enterprise and working on other international projects, always trying to help others to improve their code and project usability. When not programming the Web, he is programming his wife and kids, always with a smile on his face, open-hearted and open-minded. He loves climbing, martial arts, meditation, and salsa.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at <[email protected]> for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
https://www.packtpub.com/mapt
Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.
Yii is a free, open source web application development framework, written in PHP5, that promotes clean DRY design and encourages rapid development. It works to streamline your application development time and helps to ensure an extremely efficient, extensible, and maintainable end product. Being extremely performance-optimized, Yii is a perfect choice for any size project. However, it has been built with sophisticated, enterprise applications in mind. You have full control over the configuration from head-to-toe (presentation-to-persistence) to conform to your enterprise development guidelines. It comes packaged with tools to help test and debug your application, and has clear and comprehensive documentation.
This book is a collection of Yii2 recipes. Each recipe is represented as a full and independent item, which showcases solutions from real web applications. So you can easily reproduce them in your environment and learn Yii2 fast and without tears. All recipes are explained with step-by-step code examples and clear screenshots. Yii2 is like a suit that looks great off the rack, but is also very easy to tailor to fit your needs. Virtually every component of the framework is extensible. This book will show how to use official extensions, extend any component, or write a new one.
This book will help you create modern web applications quickly, and make sure they perform well using examples and business logic from real life. You will deal with the Yii command line, migrations, and assets. You will learn about role-based access, security, and deployment. We'll show you how to easily get started, configure your environment, and be ready to write web applications efficiently and quickly.
Chapter 1, Fundamentals, covers how to install the Yii Framework and different ways to install it. We will introduce you to application templates: basic and advanced and what is difference between them. Then you will learn about dependency injection container. This chapter contains info about model events, which are triggered after some simple actions such as model saving and updating and another. We will learn how to use external code which will include ZendFramework, Laravel, and Sympony in examples. We will also learn how to update your yii-1.x.x based application to yii2 step-by-step. A few more recipes are available at https://www.packtpub.com/sites/default/files/downloads/4270OS_Chapter1.pdf.
Chapter 2, Routing, Controllers, and Views, teaches some handy things about the Yii URL router, controllers, and views. You will be able to make your controllers and views more flexible.
Chapter 3, ActiveRecord, Model, and Database, discusses the three main methods to work with databases in Yii: Active Record, query builder, and direct SQL queries through DAO. All three are different in terms of syntax, features, and performance. In this chapter we will learn how to work with the database efficiently, when to use models and when not to, how to work with multiple databases, how to automatically preprocess Active Record fields, and how to use powerful database criteria.
Chapter 4, Forms, covers how Yii makes working with forms a breeze and the documentation on it is almost complete. Still, there are some areas that need clarification and examples.
Chapter 5, Security, discusses how to keep your application secure according to the general web application security principle "filter input, escape output." We will cover topics such as creating your own controller filters, preventing XSS, CSRF, and SQL injections, escaping output, and using role-based access control.
Chapter 6, RESTful Web Services, covers how to write RESTful Web Services using Yii2 and built-in features.
Chapter 7, Official Extensions, explains us how to install and use official extensions in your project. You will learn how to write your own extension and share it for another developers.
Chapter 8, Extending Yii, covers not only how to implement your own Yii extension, but also how to make your extension reusable and useful for the community. In addition, we will focus on many things you should do in order to make your extension as efficient as possible.
Chapter 9, Performance Tuning, teaches some best practices of developing an application that will run smoothly until you have very high loads. Yii is one of the fastest frameworks out there. Still, when developing and deploying an application, it is good to have some extra performance for free, as well as following best practices for the application itself. In this chapter, we will see how to configure Yii to gain extra performance. In addition, we will learn some best practices for developing an application that will run smoothly until we have very high loads.
Chapter 10, Deployment, covers various tips, which are especially useful on application deployment and when developing an application in a team, or when you just want to make your development environment more comfortable.
Chapter 11, Testing, teaches us how to use the best technologies for testing such as Codeception, PhpUnit, Atoum, and Behat. You will be introduced how to write simple tests and how to avoid regression errors in your applicaiton.
Chapter 12, Debugging, Logging, and Error Handling, discusses review logging, analyzing the exception stack trace, and implementing our own error handler. It is not possible to create a bug-free application if it is relatively complex, so developers have to detect errors and deal with them as fast as possible. Yii has a good set of utility features to handle logging and handling errors. Moreover, in the debug mode, Yii gives you a stack trace if there is an error. Using it, you can fix errors faster.
In order to run the examples in this book, the following software will be required:
This book is for developers with good PHP5 knowledge and MVC-frameworks who have tried to develop applications using the Yii 1.x.x version. This book will be very useful for all those who would like to try Yii2, or those who are afraid to move from Yii 1.x.x. to Yii2. If you have still not tried Yii2, this book is definitely for you!
In this book, you will find several headings that appear frequently (Getting ready, How to do it..., How it works..., There's more..., and See also).
To give clear instructions on how to complete a recipe, we use these sections as follows:
This section tells you what to expect in the recipe, and describes how to set up any software or any preliminary settings required for the recipe.
This section contains the steps required to follow the recipe.
This section usually consists of a detailed explanation of what happened in the previous section.
This section consists of additional information about the recipe in order to make the reader more knowledgeable about the recipe.
This section provides helpful links to other useful information for the recipe.
In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.
Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "we are defining an alias parameter that should be specified in the URL after /page/."
A block of code is set as follows:
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
Any command-line input or output is written as follows:
New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "Generate a Post model using Gii with an enabled Generate ActiveQuery option that generates the PostQuery class."
Warnings or important notes appear in a box like this.
Tips and tricks appear like this.
Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.
To send us general feedback, simply e-mail <[email protected]>, and mention the book's title in the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
You can download the code files by following these steps:
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Yii2-Application-Development-Cookbook-Third-Edition. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from http://www.packtpub.com/sites/default/files/downloads/Yii2ApplicationDevelopmentCookbookThirdEdition_ColorImages.pdf.
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.
To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.
Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at <[email protected]> with a link to the suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring you valuable content.
If you have a problem with any aspect of this book, you can contact us at <[email protected]>, and we will do our best to address the problem.
In this chapter, we will cover the following topics:
In this chapter we will cover how to install Yii Framework and about possible techniques of installation. We will introduce you to application templates: basic and advanced and their difference between them. Then you will learn about dependency injection container. This chapter contains info about model events, which trigger after some actions such as model saving, updating and others. We will learn how to use external code which will include ZendFramework, Laravel, or Symfony. We will also be learning about how to update your yii-1.x.x based application to yii2 step-by-step.
Yii2 is a modern PHP framework provided as a Composer package. In this recipe, we will install the framework via the Composer package manager and configure the database connection for our application.
First of all, install the Composer package manager on your system.
Note: If you use the OpenServer application on Windows, than the composer command already exists in the OpenServer terminal.
In Mac or Linux download the installer from https://getcomposer.org/download/ and install it globally by using the following command:
In Windows without OpenServer download and run Composer-Setup.exe from the https://getcomposer.org/doc/00-intro.md page.
If you do not have administrative privileges on the system then as an alternative you can just download the https://getcomposer.org/composer.phar raw file and use the php composer.phar call instead of single the composer command.
After installation run in your terminal:
Or (if you just download archive) its alternative:
When the installation succeeds you will see the following response:
Right now you can install any package from the https://packagist.org repository.
You can install basic or advanced application templates. In order to learn about the differences between the templates see the Application templates recipe.
Note that during installation the Composer package manager gets a lot of information from the GitHub site. GitHub may limit requests for anonymous users. In this case Composer asks you to input your access token. You should just register the https://github.com site and generate a new token via the https://github.com/blog/1509-personal-api-tokens guide.
Carry out the following steps for installing basic project template:
It provides a simple way to load related non-PHP packages (JavaScript and CSS) from the Bower repository.
Create a new application in the new basic directory:Note: PHP in command-mode and in web-interface mode can use different php.ini files with different configurations and different extensions.
For permanent working create a new host in your server (Apache, Nginx, and so on) and set the web directory as a document root of the host.
Carry out the following steps for installing advanced project template:
It provides a simple way to load related non-PHP packages (JavaScript and CSS) from the Bower repository.
Create a new application in the new basic directory:During initialization select the Development environment.
Check that your PHP contains the required extensions:Note: PHP in command-line mode and in web-interface mode can use different php.ini files with different configuration and different extensions.
This command will automatically create a user table in your database.
Try to run a frontend application by the following console command:Then run the backend in an other terminal window:
Create two new hosts for backend and frontend application in your server (Apache, Nginx, and so on) and set the backend/web and frontend/web directories as document roots of the hosts.
First of all, we installed the Composer package manager and the Bower asset plugin.
After we installed the application via the composer create-project command, the command creates a new empty directory, clones the source code of application template and loads all its inner dependencies (framework and other components) into the vendor subdirectory.
If needed, we will initialize application configuration and set up a new database.
We can check system requirements via running the requirements.php script in console or browser mode.
And after cloning of the code we can configure our own PHP server to work with the web directories as the server's document roots.
Yii2 has two application templates for development: basic and advanced. What is the difference between basic and advanced templates?
The names are confusing. Some people in the end choose basic because advanced may sound repulsive. In this chapter we will look at the differences.
Please refer to the Installing the framework recipe's How to do it… section to understand and learn how to install different templates.
The advanced template has a custom system of configurations. It is developed so that a team can work together on a project but each developer can customize their own configurations for development, testing, and other environments.
Configuration environments can be complicated and normally aren't used when you develop alone.
The advanced template has frontend and backend folders for the frontend and backend parts of the web application accordingly. So you can configure a separate host for each folder and thereby isolate the frontend and backend part.
This is a simple way to organize files into directories and configure the web server. You can easily do the same thing in the basic template.
Neither front/back-end separation nor user management is on its own a good reason to choose the advanced template. It's better to adapt these features to your app—you'll learn more and won't get the difficult config problem.
If you will be working on the project with a team and you might need configuration flexibility, use different environments to develop and in this case a better choice would be the advanced application template. If you will be working alone and your project is simple you should choose the basic application template.
