Mastering Yii
()
About this ebook
About This Book
- Learn to work with the key aspects of Yii Framework 2
- Explore how to create RESTful APIs with Yii
- Incorporate codeception with Yii2 to test your code thoroughly
Who This Book Is For
This book is for Yii Framework developers who want to quickly master Yii2. This book assumes some familiarity with Yii2, PHP 5, and HTML5.
What You Will Learn
- Explore Yii2’s conventions and learn how to properly configure Yii2
- Create both web and console applications
- Reduce development time by learning to create classes automatically with Gii, Yii2’s automatic code generation tool
- Use Yii2’s database migration tool
- Manage and access databases with Active Record, DAO, and Query Builder
- Handle user authentication and authorization within Yii2
- Create RESTful APIs with Yii Framework 2
- Test applications automatically with codeception
In Detail
The successor of Yii Framework 1.1, Yii2 is a complete rewrite of Yii Framework, one of the most popular PHP 5 frameworks for making modern web applications. The update embraces the best practices and protocols established with newer versions of PHP, while still maintaining the simple, fast, and extendable behavior found in its predecessor.
This book has been written to enhance your skills and knowledge with Yii Framework 2. Starting with configuration and how to initialize new projects, you’ll learn how to configure, manage, and use every aspect of Yii2 from Gii, DAO, Query Builder, Active Record, and migrations, to asset manager. You'll also discover how to automatically test your code using codeception.
With this book by your side, you’ll have all the skills you need to quickly create rich modern web and console applications with Yii2.
Style and approach
This book is a step-by-step guide to mastering every aspect of Yii Framework 2. Each chapter outlines a new set of tools along with code that can be used to efficiently create modern web and console applications
Related to Mastering Yii
Related ebooks
Yii2 Application Development Cookbook - Third Edition Rating: 0 out of 5 stars0 ratingsYii2 By Example Rating: 0 out of 5 stars0 ratingsLearning Yii Testing Rating: 1 out of 5 stars1/5PHP5 and MySQL Bible Rating: 3 out of 5 stars3/5Instant Play Framework Starter Rating: 0 out of 5 stars0 ratingsPHP 8: The Modern Web Developer's Guide Rating: 0 out of 5 stars0 ratingsPractical Django 2 and Channels 2: Building Projects and Applications with Real-Time Capabilities Rating: 0 out of 5 stars0 ratingsCSS Mastery: Styling Web Pages Like a Pro Rating: 0 out of 5 stars0 ratingsBluetooth Low Energy LE Complete Self-Assessment Guide Rating: 0 out of 5 stars0 ratingsRedmine Cookbook Rating: 0 out of 5 stars0 ratingsCode review Complete Self-Assessment Guide Rating: 0 out of 5 stars0 ratingsMicrosoft Team Foundation Server 2015 Cookbook Rating: 0 out of 5 stars0 ratingsMicrosoft Conversational AI Platform for Developers: End-to-End Chatbot Development from Planning to Deployment Rating: 0 out of 5 stars0 ratingsOdoo 10 Development Essentials Rating: 0 out of 5 stars0 ratingsBuilding Websites with VB.NET and DotNetNuke 4 Rating: 1 out of 5 stars1/5Professional Plone 4 Development Rating: 3 out of 5 stars3/5MODx Web Development Rating: 0 out of 5 stars0 ratingsPython Architecture Patterns: Master API design, event-driven structures, and package management in Python Rating: 0 out of 5 stars0 ratingsGetting Started with Oracle Data Integrator 11g: A Hands-On Tutorial Rating: 5 out of 5 stars5/5Learning PHP 7 Rating: 0 out of 5 stars0 ratingsFederated Learning with Python: Design and implement a federated learning system and develop applications using existing frameworks Rating: 0 out of 5 stars0 ratingsCodeIgniter 1.7 Rating: 0 out of 5 stars0 ratingsGrails 1.1 Web Application Development Rating: 0 out of 5 stars0 ratingsNginx HTTP Server Rating: 4 out of 5 stars4/5WordPress 3 Plugin Development Essentials Rating: 4 out of 5 stars4/5Learning Go Programming Rating: 0 out of 5 stars0 ratingsLearning Nagios - Third Edition Rating: 0 out of 5 stars0 ratingsLearning Python Rating: 5 out of 5 stars5/5
Internet & Web For You
Coding All-in-One For Dummies Rating: 4 out of 5 stars4/5No Place to Hide: Edward Snowden, the NSA, and the U.S. Surveillance State Rating: 4 out of 5 stars4/5Social Engineering: The Science of Human Hacking Rating: 3 out of 5 stars3/5How to Be Invisible: Protect Your Home, Your Children, Your Assets, and Your Life Rating: 4 out of 5 stars4/5How to Disappear and Live Off the Grid: A CIA Insider's Guide Rating: 0 out of 5 stars0 ratingsCoding For Dummies Rating: 5 out of 5 stars5/5The Gothic Novel Collection Rating: 5 out of 5 stars5/5Six Figure Blogging Blueprint Rating: 5 out of 5 stars5/5The $1,000,000 Web Designer Guide: A Practical Guide for Wealth and Freedom as an Online Freelancer Rating: 4 out of 5 stars4/5The Hacker Crackdown: Law and Disorder on the Electronic Frontier Rating: 4 out of 5 stars4/5The Mega Box: The Ultimate Guide to the Best Free Resources on the Internet Rating: 4 out of 5 stars4/5Podcasting For Dummies Rating: 4 out of 5 stars4/5Everybody Lies: Big Data, New Data, and What the Internet Can Tell Us About Who We Really Are Rating: 4 out of 5 stars4/5HTML in 30 Pages Rating: 5 out of 5 stars5/5Ultimate guide for being anonymous: Avoiding prison time for fun and profit Rating: 5 out of 5 stars5/5Grokking Algorithms: An illustrated guide for programmers and other curious people Rating: 4 out of 5 stars4/5Beginner's Guide To Starting An Etsy Print-On-Demand Shop Rating: 0 out of 5 stars0 ratingsAn Ultimate Guide to Kali Linux for Beginners Rating: 3 out of 5 stars3/5Stop Asking Questions: How to Lead High-Impact Interviews and Learn Anything from Anyone Rating: 5 out of 5 stars5/5How to Destroy Surveillance Capitalism Rating: 4 out of 5 stars4/5Get Rich or Lie Trying: Ambition and Deceit in the New Influencer Economy Rating: 0 out of 5 stars0 ratingsThe Beginner's Affiliate Marketing Blueprint Rating: 4 out of 5 stars4/5Cybersecurity For Dummies Rating: 5 out of 5 stars5/5Content Chemistry: The Illustrated Handbook for Content Marketing Rating: 5 out of 5 stars5/5Tor and the Dark Art of Anonymity Rating: 5 out of 5 stars5/5Cybersecurity All-in-One For Dummies Rating: 0 out of 5 stars0 ratingsTiny Python Projects: Learn coding and testing with puzzles and games Rating: 4 out of 5 stars4/5Python QuickStart Guide: The Simplified Beginner's Guide to Python Programming Using Hands-On Projects and Real-World Applications Rating: 0 out of 5 stars0 ratings
Reviews for Mastering Yii
0 ratings0 reviews
Book preview
Mastering Yii - PortwoodII Charles R.
Table of Contents
Mastering Yii
Credits
About the Author
About the Reviewer
www.PacktPub.com
Support files, eBooks, discount offers, and more
Why subscribe?
Free access for Packt account holders
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. Composer, Configuration, Classes, and Path Aliases
Composer
Configuration
Requirements checker
Entry scripts
Web entry script
Configuration files
Web and console configuration files
Database configuration
Parameter configuration
Environment configuration
Setting up our application environment
Setting the web environment for NGINX
Setting the web environment for Apache
Components and objects
Components
Objects
Path aliases
Summary
2. Console Commands and Applications
Configuration and usage
Entry script
Configuration
Setting the console environment
Running console commands
Built-in console commands
The help command
The asset command
The cache command
The fixture command
The Gii command
The message command
The migration command
Creating console commands
Generating help information
Passing command-line arguments
Exit codes
Formatting
Summary
3. Migrations, DAO, and Query Building
Connecting to databases
Additional configuration options
Writing database migrations
An overview of schema
Writing migrations
Running migrations
Altering a database schema
Database access objects
Querying for data
Quoting table and column names
Executing queries
Parameter binding
Transactions
Query Builder
Query construction methods
The select method
The from method
The where method
The string format
The hash format
The operator format
Ordering results
Limiting and offsetting data
Grouping and having
Joins and unions
Executing queries
Examining queries
Iterating over query results
Data providers and data widgets
Data replication and load balancing
Summary
4. Active Record, Models, and Forms
Configuring Gii
Gii for web applications
Gii for console applications
Active Record
The Active Record pattern
Creating Active Record classes
Creating active record classes with Gii
Using Gii's web interface
Using Gii's console interface
Working with Active Record
Model validation rules
Adding custom validators
Customizing validator error messages
Working with validation errors
Manually executing validation rules
Model attribute labels
Active Record relationships
Using multiple database connections with Active Record
Behaviors in Active Record
Working with Active Record
Querying data
Data access
Saving data
Creating new records
Deleting data
Active Record events
Models
Model attributes
Scenarios
Forms
Generating forms with Gii
Generating forms with Gii's web interface
Generating forms with Gii's console interface
Using forms
ActiveForm and input types
Summary
5. Modules, Widgets, and Helpers
Modules
Module components
The module class structure
Controllers
Views and layouts
Registering modules
Dynamically registering modules
Bootstrapping modules
Accessing modules
Managing modules with Composer
Modules in summary
Widgets
Using widgets
Commonly used built-in widgets
Bootstrap widgets
jQuery UI widgets
Yii-specific widgets
Creating custom widgets
A summary of widgets
Helpers
The URL helper
The HTML helper
The JSON helper
The Markdown helper
Variable dumping
Inflector
FileHelper
Summary
6. Asset Management
Asset bundles
Using asset bundles
Configuration
Asset mapping
Asset types and locations
Asset options
Asset publication
Client cache management with asset bundles
Using preprocessor with asset bundles
The asset command line tool
Third-party asset tools
NodeJS
Bower
Grunt
Summary
7. Authenticating and Authorizing Users
Authentication of users
Implementing the user identity interface
Cookie-based authentication
Working with user identities
Authenticating users with forms
Authorization
Access control filters
Role-based access control
Configuring RBAC
Creating permissions and permission relationships
Custom authorization rules
Checking if a user has access to a role
Flash messages
Hashing and encryption
Hashing and verifying passwords
Data encryption and decryption
Data hashing
Summary
8. Routing, Responses, and Events
Routing
Default and catch all routes
Custom routes and URL rules
Parameterizing routes
URL suffixes
HTTP method-specific URL rules
Custom URL rule classes
Dynamic rule generation
Requests
Retrieving request parameters and data
Request headers and cookies
Retrieving client and URL information
Responses
Setting status codes
Web exceptions
Setting response headers
The response body
Redirection
The file output
Events
Event handlers
Triggering events
Class-level events
Global events
Summary
9. RESTful APIs
ActiveController
Configuring ActiveController display fields
Data serialization within responses
Disabling ActiveController actions
Customizing ActiveController actions
Authentication filters
HTTP basic authentication
Query parameter authentication
OAuth2 authentication
Composite authentication
Custom authentication filters
Action-specific authentication
Checking access
Verb filters
Cross-origin resource headers
Rate Limiting
Error handling
Custom API controllers
Returning data
Response Formatting
Summary
10. Testing with Codeception
Reasons for testing
How to approach testing
Testing manually
Testing a few core components
Test-driven development
Configuring Codeception with Yii2
Unit testing
Generating unit tests
Unit test examples
Testing User model methods
Functional testing
Setting up functional tests
Generating functional tests
Examples of functional tests
Acceptance testing
Setting up acceptance testing
Examples of acceptance tests
Fixtures
Creating fixtures
Defining fixtures
Using fixtures in unit tests
Automatic change testing
Summary
11. Internationalization and Localization
Configuring Yii2 and PHP
The intl extension
The application language
Programmatically setting the application language
Dynamically setting the application language
Message translations
Message sources
Default translations
Framework messages
Handling missing translations
Generating message files
Message formatting
Viewing file translations
Module translations
Widget translations
Summary
12. Performance and Security
Caching
Caching data
Caching dependencies
Database query caching
Fragment caching
Page caching
HTTP caching
Caching database schema
General performance enhancements
Enabling OPCache
Optimizing Composer dependencies
Upgrading to PHP 7
Switch to Facebook's HHVM
Security considerations
Certificates
Cookies
Protecting against cross-site scripting
Enabling cross-site request forgery protection
Summary
13. Debugging and Deploying
Debugging
Logging
Benchmarking
Error handling
Handling errors within non HTML responses
Debugging with the Yii2 debug extension
Deploying
Summary
Index
Mastering Yii
Mastering Yii
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 author, 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: January 2016
Production reference: 1210116
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78588-242-5
www.packtpub.com
Credits
Author
Charles R. Portwood II
Reviewer
Tomasz Trejderowski
Acquisition Editor
Divya Poojari
Content Development Editor
Anish Dhurat
Technical Editor
Edwin Moses
Copy Editor
Stuti Srivastava
Project Coordinator
Bijal Patel
Proofreader
Safis Editing
Indexer
Priya Sane
Production Coordinator
Shantanu N. Zagade
Cover Work
Shantanu N. Zagade
About the Author
Charles R. Portwood II has over 10 years of experience developing modern web applications and is well versed in integrating PHP with native mobile applications. An avid proponent of Yii Framework and open source software, Charles has contributed multiple guides, extensions, and applications to the Yii community. In addition to being a programmer, he is also a Linux system administrator.
About the Reviewer
Tomasz Trejderowski is a middle-aged developer from Poland who has hands-on experience working with many programming languages and in diverse IT-related areas. He has been programming computers since the very first Commodore 64 and thus, he poses over 20 years of software development experience. You can access repositories and contributions on his GitHub profile, at http://github.com/trejder.
He is a full-time business analyst and free-time PhoneGap/Yii2 developer and blogger. He is also a mobile market entrepreneur, constantly working on some innovative projects. For more information, visit his company website at http://www.gaman.pl or his blog network at http://www.acrid.pl/.
He is a happy husband of his wonderful wife and father of two beautiful daughters.
www.PacktPub.com
Support files, eBooks, discount offers, and more
For support files and downloads related to your book, please visit www.PacktPub.com.
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
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://www2.packtpub.com/books/subscription/packtlib
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.
Why subscribe?
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
Free access for Packt account holders
If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view 9 entirely free books. Simply use your login credentials for immediate access.
Preface
Yii Framework 2 (Yii2) is the successor to the popular Yii framework. Like its successor, Yii2 is an open source, high-performance rapid development framework designed to create modern, scalable, and performant web applications and APIs.
Designed for both developers with no exposure to Yii and Yii2 and for Yii framework developers looking to become experts with Yii2, this book will serve as your guide to becoming a master of Yii. From initialization and configuration to debugging and deployment, this book will be your guide to becoming a master of all aspects of this powerful framework.
What this book covers
Chapter 1, Composer, Configuration, Classes, and Path Aliases, covers the basics of a Yii2 application. In this chapter, you'll learn the core conventions of Yii2 and how to configure it as a multi-environment application. You'll also discover how to use Composer, a dependency management tool for managing your applications' software dependencies.
Chapter 2, Console Commands and Applications, focuses on how to use the built-in Yii2 console commands as it guides you through creating your own commands.
Chapter 3, Migrations, DAO, and Query Building, teaches you how to create migrations in Yii2 and how to interact with your database using database access objects (DAO) and how to use Yii2's query builder.
Chapter 4, Active Record, Models, and Forms, teaches you how to create and use Active Record to effortlessly interact with a database. Furthermore, you'll also discover how to create models to represent information not stored in databases and how to create web forms based upon Active Record models and normal models.
Chapter 5, Modules, Widgets, and Helpers, covers how to incorporate modules inside of our application. This chapter will also cover how to create and use dynamic widgets and will additionally cover Yii2's powerful helper classes.
Chapter 6, Asset Management, focuses on how to create and manage our assets using asset bundles and how to manage our assets using the asset command. This chapter also covers several strategies to build and generate our asset library using powerful tools such as Node Package Manage and Bower.
Chapter 7, Authenticating and Authorizing Users, teaches you how to verify the authenticity of users in Yii2 using several common authentication schemes (such as OAuth authentication, basic HTTP authentication, and header authentication) as well as shows you how to grant them access to specific sections of your applications.
Chapter 8, Routing, Responses, and Events, focuses on how Yii2's routing and response classes work in Yii2. In this chapter, we'll cover how to handle data both in and out of our application and discover how to tap into Yii2's powerful event system.
Chapter 9, RESTful APIs, talks about how to quickly and effortlessly extend your application with a RESTful JSON and XML API using Yii2's ActiveController class.
Chapter 10, Testing with Codeception, helps you learn how to create unit, functional, and acceptance tests for your applications using a powerful testing tool called Codeception. In this chapter, you'll also learn how to create fixtures to represent your data for testing purposes.
Chapter 11, Internationalization and Localization, covers how to localize our applications and build them to support multiple languages. Additionally, you will master how to create and manage translation files using Yii2 console commands.
Chapter 12, Performance and Security, covers many ways to improve the performance of your Yii2 application and how to keep it secure against modern day attacks on web applications.
Chapter 13, Debugging and Deploying, helps you become well-versed in how to debug your Yii2 applications using both application logging and the Yii2 debug tool. Furthermore, you will discover the fundamentals of deploying your Yii2 applications in a seamless and non-disruptive fashion.
What you need for this book
To ensure a consistent development environment and prevent unnecessary alterations to your host operation system, it is highly recommended that you run all commands within a Linux virtual machine. This will ensure that your output both in your web browser and from your command line matches the output that is presented in this book. As setting up this environment on your own can be a daunting task, prebuilt virtual machines that use VirtualBox and Vagrant are provided to make this setup process easy.
To get started with this book, you should be running the latest version of either Microsoft Windows 7, 8, 8.1 or 10, Apple OS X 10.9 or higher, or a Linux operating system that can run virtual machines, such as Ubuntu 14.04 LTS. Additionally, you will need to install the latest version of VirtualBox (available at https://www.virtualbox.org/wiki/Downloads) and Vagrant (available at https://www.vagrantup.com/downloads.html).
Note
After installing these software dependencies, you may need to restart your computer for the changes to take effect.
After installing VirtualBox and Vagrant, you can then create a new dedicated development environment by opening a new command line or terminal window, creating a new directory for the chapter, and then running the following command to create your virtual machine development environment. These commands will download a prebuilt virtual machine containing all the software required to get you started and start your new development environment:
vagrant init charlesportwoodii/php56_trusty64 vagrant up --provider virtualbox vagrant ssh
Note
More information on this specific Vagrant box can be found at https://atlas.hashicorp.com/charlesportwoodii/boxes/php56_trusty64.
Note that if you are on Windows, you may need a tool such as PuTTy to connect to your virtual machine over SSH. More information on how to connect to your new virtual machine over SSH on Windows can be found at http://docs-v1.vagrantup.com/v1/docs/getting-started/ssh.html.
Once your new Vagrant box has started, you can access the files of this virtual machine over SSH and access your webroot directory by opening a new browser window and navigating to http://localhost:8080. By default, when you open this web page, you will see the output of phpino().
Tip
Depending upon your operating system security settings, your computer may prompt or block you from accessing port 8080 on your computer. Ensure that you configure your firewall settings if you are facing issues and ensure that port 8080 is open on your computer and that VirtualBox can forward connections from your host operating system to your guest operating system.
As Yii2 is fully compatible with PHP7, it is strongly suggested that you develop and test your web applications against PHP7 as well. The following commands will allow you to provision a PHP7 Vagrant box:
vagrant init charlesportwoodii/php7_trusty64 vagrant up --provider virtualbox vagrant ssh
Tip
As these virtual machines automatically configure port forwarding, it is recommended that you only run a single virtual machine at a time. Refer to the Vagrant documentation for a complete list of commands and configuration options at https://docs.vagrantup.com/v2.
Who this book is for
Mastering Yii is for intermediate to experienced software developers who want to quickly master Yii2. This book assumes some familiarity with PHP 5, HTML5, and rudimentary software development practices and methodologies.
Conventions
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: This script tells Composer that when the create-project command is run, it should run the postCreateProject static function.
A block of code is set as follows:
scripts
: {
post-create-project-cmd
: [
yii\\composer\\Installer::postCreateProject
]
}
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
// Define our application_env variable as provided by nginx/apache if (!defined('APPLICATION_ENV')) { if (getenv('APPLICATION_ENV') != false) define('APPLICATION_ENV', getenv('APPLICATION_ENV')); else define('APPLICATION_ENV', 'prod'); }
$env = require(__DIR__ . '/config/env.php');
Any command-line input or output is written as follows:
$ ./yii fixture/load
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: Once we have specified all the necessary attributes, we can click on the Preview button to preview our form, and then we can click on the Generate button to generate the source code.
Note
Warnings or important notes appear in a box like this.
Tip
Tips and tricks appear like this.
Reader feedback
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 <feedback@packtpub.com>, 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.
Customer support
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.
Downloading the example code
The latest and most up to date copies of source code for this book is maintained on the Packt website: http://www.packtpub.com and on GitHub at https://github.com/masteringyii, for each chapter where applicable.
Errata
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
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 <copyright@packtpub.com> with a link to the suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring you valuable content.
Questions
If you have a problem with any aspect of this book, you can contact us at <questions@packtpub.com>, and we will do our best to address the problem.
Chapter 1. Composer, Configuration, Classes, and Path Aliases
Before diving into Yii Framework 2, we need to take a look at how it is installed, how it is configured, and what the core building blocks of the framework are. In this chapter, we'll go over how to install the framework itself and prebuilt applications via a package management tool called Composer. We'll also cover some common configurations of both Yii Framework 2 and our web server, including making our applications aware of the environment they are running on and responding appropriately to that environment.
Note
The most common ways to reference Yii Framework 2 are Yii Framework 2, YF2, and Yii2. We'll be using these terms interchangeably throughout the book.
Composer
There are several different ways to install Yii2, ranging from downloading the framework from source control (typically, from GitHub at https://github.com/yiisoft/yii2) to using a package manager such as Composer. With modern web applications, Composer is the preferred method to install Yii2 as it enables us to install, update, and manage all dependencies and extensions for our application in an automated fashion. Additionally, using Composer, we can ensure that Yii Framework 2 is kept up to date with the latest security and bug fixes. Composer can be installed by following the instructions on https://getcomposer.org. Typically, this process looks as follows:
curl -sS https://getcomposer.org/installer | php
Alternatively, if you don't have cURL available on your system, it can be installed through PHP itself:
php -r readfile('https://getcomposer.org/installer');
| php
Once installed, we should move Composer to a more centralized directory so that we can call it from any directory on our system. Installing Composer from a centralized directory rather than on a per-project basis has several advantages:
It can be called anywhere from any project. When working with multiple projects, we can ensure that we use the same dependency manager each time and for every project.
In a centralized directory, Composer only needs to be updated once rather than in every project we are working on.
Dependency managers are rarely considered code that should be pushed to your DCVS repository. Keeping the composer.phar file out of your repository reduces the amount of code you need to commit and push and ensures that your source code remains isolated from your package manager code.
By installing Composer from a centralized directory, we can ensure that Composer is always available, which saves us a step each time we clone a project that depends on Composer.
A good directory to move Composer to is /usr/local/bin, as shown in the following example:
mv composer.phar /usr/local/bin/composer chmod a+x /usr/local/bin/composer
Tip
Throughout this book, we'll be using Unix-style commands when referencing command-line arguments. Consequently, some commands may not work on Windows. If you decide to set up a Windows environment, you might need to use Composer-Setup.exe (available at https://getcomposer.org/Composer-Setup.exe) to get Composer configured for your system. If you have any issues getting Composer to run on your system, ensure that you check out the Composer documentation available at https://getcomposer.org/doc/.
Alternatively, if you have Composer installed on your system already, ensure that you update it to the latest version by running this:
composer self-update
Tip
The commands that we use through this book are based on the assumption that you have sufficient privileges to run them. On Unix-like systems, you may need to preface some commands with sudo in order to execute the command with a high permissions set. Alternatively if you are running these commands on Windows, you should ensure that you are running the listed commands in a command prompt that has elevated privileges. Ensure that you follow best practices when using sudo and when using elevated command prompts in order to ensure your system stays secure.
Once Composer is installed, we'll need to install a global plugin called The Composer Asset Plugin (available at https://github.com/francoispluchino/composer-asset-plugin). This plugin enables Composer to manage asset files for us without the need to install additional software (these programs are Bower, an asset dependency manager created by Twitter, and Node Package Manager, or NPM, which is a JavaScript dependency manager).
composer global require fxp/composer-asset-plugin:1.0.0
Tip
Due to the GitHub API's rate limiting, during installation, Composer may ask you to enter your GitHub credentials. After entering your credentials, Composer will request a dedicated API key from GitHub that can be used for future installations. Ensure that you check out the Composer documentation at https://getcomposer.org/doc/ for more information.
With Composer installed, we can now instantiate our application. If we want to install an existing Yii2 package, we can simply run the following:
composer create-project --prefer-dist
Using the Yii2 basic app as an example, this command will look like this:
composer create-project --prefer-dist yiisoft/yii2-app-basic basic
After running the command, you should see output similar to the following:
Installing yiisoft/yii2-app-basic (2.0.6) - Installing yiisoft/yii2-app-basic (2.0.6) Downloading: 100% Created project in basic Loading composer repositories with package information Installing dependencies (including require-dev) - Installing yiisoft/yii2-composer (2.0.3) - Installing ezyang/htmlpurifier (v4.6.0) - Installing bower-asset/jquery (2.1.4) - Installing bower-asset/yii2-pjax (v2.0.4) - Installing bower-asset/punycode (v1.3.2) - Installing bower-asset/jquery.inputmask (3.1.63) - Installing cebe/markdown (1.1.0) - Installing yiisoft/yii2 (2.0.6) - Installing swiftmailer/swiftmailer (v5.4.1) - Installing yiisoft/yii2-swiftmailer (2.0.4) - Installing yiisoft/yii2-codeception (2.0.4) - Installing bower-asset/bootstrap (v3.3.5) - Installing yiisoft/yii2-bootstrap (2.0.5) - Installing yiisoft/yii2-debug (2.0.5) - Installing bower-asset/typeahead.js (v0.10.5)