Book Image

Yii2 Application Development Cookbook - Third Edition

By : Sergey Ivanov, Andrew Bogdanov, Dmitry Eliseev
Book Image

Yii2 Application Development Cookbook - Third Edition

By: Sergey Ivanov, Andrew Bogdanov, Dmitry Eliseev

Overview of this book

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.
Table of Contents (19 chapters)
Yii2 Application Development Cookbook Third Edition
Credits
About the Authors
About the Reviewer
www.PacktPub.com
Preface
Index

Using external code


Package repositories, PSR standards, and social coding provide us with lots of high-quality reusable libraries and other components with free licenses. We can just install any external component in project instead of reengineering them from scratch. It improves development performance and makes for higher-quality code.

Getting ready

Create a new application by using the Composer package manager as described in the official guide at http://www.yiiframework.com/doc-2.0/guide-start-installation.html.

How to do it…


In this recipe we will try to attach some libraries manually and via Composer.

Installing a library via Composer

When you use NoSQL or other databases without autoincrement primary keys, you must generate unique identifiers manually. For example, you can use Universally Unique Identifier (UUID) instead of a numerical one. Let's do it:

  1. Install https://github.com/ramsey/uuid component via Composer:

    composer require ramsey/uuid
    
  2. Create a demonstration console controller:

    <?php
    namespace app\commands;
    
    use Ramsey\Uuid\Uuid;
    use yii\console\Controller;
    
    class UuidController extends Controller
    {
        public function actionGenerate()
        {
            $this->stdout(Uuid::uuid4()->toString() . PHP_EOL);
            $this->stdout(Uuid::uuid4()->toString() . PHP_EOL);
            $this->stdout(Uuid::uuid4()->toString() . PHP_EOL);
            $this->stdout(Uuid::uuid4()->toString() . PHP_EOL);
            $this->stdout(Uuid::uuid4()->toString() . PHP_EOL);
        }
    }
  3. And just run it:

    ./yii uuid/generate
  4. If successful, you'll see the following output:

    25841e6c-6060-4a81-8368-4d99aa3617dd
    fcac910a-a9dc-4760-8528-491c17591a26
    4d745da3-0a6c-47df-aee7-993a42ed915c
    0f3e6da5-88f1-4385-9334-b47d1801ca0f
    21a28940-c749-430d-908e-1893c52f1fe0
  5. That's it! Now you can use the Ramsey\Uuid\Uuid class in your project.

Installing libraries manually

We can install a library automatically when it is provided as a Composer package. In other cases we must install it manually.

For example, create some library examples:

  1. Create the awesome/namespaced/Library.php file with the following code:

    <?php
    namespace awesome\namespaced;
    
    class Library
    {
        public function method()
        {
            return 'I am an awesome library with namespace.';
        }
    }
  2. Create the old/OldLibrary.php file:

    <?php
    class OldLibrary
    {
        function method()
        {
            return 'I am an old library without namespace.';
        }
    }
  3. Create a set of functions as an old/functions.php file:

    <?php
    function simpleFunction()
    {
        return 'I am a simple function.';
    }

    And now set up this file in our application:

  4. Define the new alias for the awesome library namespace root in the config/web.php file (in aliases section):

    $config = [
        'id' => 'basic',
        'basePath' => dirname(__DIR__),
        'bootstrap' => ['log'],
        'aliases' => [
            '@awesome' => '@app/awesome',
        ],
        'components' => [
            // …
        ],
        'params' => // …
    ];

    or via the setAlias method:

    Yii::setAlias('@awesome', '@app/awesome');
  5. Define a simple class file path at the top of the config/web.php file:

    Yii::$classMap['OldLibrary'] = '@old/OldLibrary.php';
  6. Configure autoloading of the functions.php file in composer.json:

    "require-dev": {
        ...
    },
    "autoload": {
        "files": ["old/functions.php"]
    },
    "config": {
        ...
    },

    And apply the changes:

    composer update
    
  7. And now create an example controller:

    <?php
    namespace app\controllers;
    
    use yii\base\Controller;
    
    class LibraryController extends Controller
    {
        public function actionIndex()
        {
            $awesome = new \awesome\namespaced\Library();
            echo '<pre>' . $awesome->method() . '</pre>';
    
            $old = new \OldLibrary();
            echo '<pre>' . $old->method() . '</pre>';
    
            echo '<pre>' . simpleFunction() . '</pre>';
        }
    }

    And open the page:

Using Yii2 code in other frameworks

If you want to use Yii2 framework code with other frameworks just add Yii2-specific parameters in composer.json:

{
    ...
    "extra": {
        "asset-installer-paths": {
            "npm-asset-library": "vendor/npm",
            "bower-asset-library": "vendor/bower"
        }
    }
}

And install the framework:

composer require yiisoft/yii2

Now open the entry script of your application (on ZendFramework, Laravel, Symfony, and many more), require the Yii2 autoloader, and create the Yii application instance:

require(__DIR__ . '/../vendor/autoload.php');
require(__DIR__ . '/../vendor/yiisoft/yii2/Yii.php');
$config = require(__DIR__ . '/../config/yii/web.php');
new yii\web\Application($config);

That's it! Now you can use Yii::$app instances, models, widgets and other components from Yii2.

How it works…

In the first case we just install a new Composer package in our project and use it, because its composer.json file defines all aspects of autoloading library files.

But in the second case we did not have Composer packages and registered the files in the autoloading mechanism manually. In Yii2 we can use aliases and Yii::$classMap for registering the roots of PSR-4 namespaces and for single files.

But as an alternative we can use Composer autoloader for all cases. Just define an extended autoload section in the composer.json file like this:

"autoload": {
    "psr-0": { "": "old/" },
    "psr-4": {"awesome\\": "awesome/"},
    "files": ["old/functions.php"]
}

Apply the changes using this command:

composer update

Right now you can remove aliases and $classMap definitions from your configuration files and ensure the example page still works correctly:

This example completely uses Composer's autoloader instead of the framework's autoloader.

See also