Book Image

Mastering Yii

By : Charles R. Portwood ll
Book Image

Mastering Yii

By: Charles R. Portwood ll

Overview of this book

The successor of Yii Framework 1.1, Yii 2 is a complete rewrite of Yii Framework, one of the most popular PHP 5 frameworks around 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 Yii 2.
Table of Contents (20 chapters)
Mastering Yii
Credits
About the Author
About the Reviewer
www.PacktPub.com
Preface
5
Modules, Widgets, and Helpers
13
Debugging and Deploying
Index

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 <package/name> <foldername>

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)
  - Installing phpspec/php-diff (v1.0.2)
  - Installing yiisoft/yii2-gii (2.0.4)
  - Installing fzaninotto/faker (v1.5.0)
  - Installing yiisoft/yii2-faker (2.0.3)
Writing lock file
Generating autoload files
> yii\composer\Installer::postCreateProject
chmod('runtime', 0777)...done.
chmod('web/assets', 0777)...done.
chmod('yii', 0755)...done.

Note

Your output may differ slightly due to the data cached on your system and versions of subpackages.

This command will install the Yii2 basic app to a folder called basic. When creating a new Yii2 project, you'll typically want to use the create-project command to clone "yii2-app-basic" and then develop your application from there as the basic app comes prepopulated with just about everything you need to start a new project. However, you can also create a Yii2 project from scratch that, while more complicated, gives you more control over your application's structure.

Let's take a look at the composer.json file that was created when we ran the create-project command:

{
    "name": "yiisoft/yii2-app-basic",
    "description": "Yii 2 Basic Application Template",
    "keywords": ["yii2", "framework", "basic", "application template"],
    "homepage": "http://www.yiiframework.com/",
    "type": "project",
    "license": "BSD-3-Clause",
    "support": {
        "issues": "https://github.com/yiisoft/yii2/issues?state=open",
        "forum": "http://www.yiiframework.com/forum/",
        "wiki": "http://www.yiiframework.com/wiki/",
        "irc": "irc://irc.freenode.net/yii",
        "source": "https://github.com/yiisoft/yii2"
    },
    "minimum-stability": "stable",
    "require": {
        "php": ">=5.4.0",
        "yiisoft/yii2": "*",
        "yiisoft/yii2-bootstrap": "*",
        "yiisoft/yii2-swiftmailer": "*"
    },
    "require-dev": {
        "yiisoft/yii2-codeception": "*",
        "yiisoft/yii2-debug": "*",
        "yiisoft/yii2-gii": "*",
        "yiisoft/yii2-faker": "*"
    },
    "config": {
        "process-timeout": 1800
    },
    "scripts": {
        "post-create-project-cmd": [
            "yii\\composer\\Installer::postCreateProject"
        ]
    },
    "extra": {
        "yii\\composer\\Installer::postCreateProject": {
            "setPermission": [
                {
                    "runtime": "0777",
                    "web/assets": "0777",
                    "yii": "0755"
                }
            ],
            "generateCookieValidationKey": [
                "config/web.php"
            ]
        },
        "asset-installer-paths": {
            "npm-asset-library": "vendor/npm",
            "bower-asset-library": "vendor/bower"
        }
    }
}

While most of these items (such as the name, description, license, and require blocks) are rather self-explanatory, there are a few Yii2-specific items in here that we should take note of. The first section we want to look at is the "scripts" section:

"scripts": {
    "post-create-project-cmd": [
        "yii\\composer\\Installer::postCreateProject"
    ]
}

This script tells Composer that when the create-project command is run, it should run the postCreateProject static function. Looking at the the framework source code, we see that this file is referenced in the yii2-composer package (refer to https://github.com/yiisoft/yii2-composer/blob/master/Installer.php#L232). This command then runs several post-project creation actions, namely setting the local disk permissions, generating a unique cookie validation key, and setting some asset installer paths for composer-asset-plugin.

Next, we have the "extra" block:

"extra": {
    "yii\\composer\\Installer::postCreateProject": {
        "setPermission": [
            {
                "runtime": "0777",
                "web/assets": "0777",
                "yii": "0755"
            }
        ],
        "generateCookieValidationKey": [
            "config/web.php"
        ]
    },
    "asset-installer-paths": {
        "npm-asset-library": "vendor/npm",
        "bower-asset-library": "vendor/bower"
    }
}

This section tells Composer to use these options when it runs the postCreateProject command. These preconfigured options give us a good starting point to create our applications.