Yiinitializr: The Library

Introduction

For those who have created a project boilerplate with Yiinitializr site, you will find that is not just a project boilerplate what you just downloaded. Within the boilerplate comes a library named: Yiinitializr (not very original I know). The classes within this tiny library are simple, yet powerful, and will help you build your own project setup, the one that really fits your needs for your Yii application.

The Classes Explained

The Yiinitializr classes will help boost your application installation with ease and also to run Yii applications from its bootstrap files on a much cleaner way that the framework currently proposes. Let’s have a look at the following example:

// if installed via composer (pretty neat right?)
require('./../../common/lib/vendor/autoload.php');
Yiinitializr\Helpers\Initializer::create('./../', 'frontend', array(
    // will override frontend configuration file
    __DIR__ .'/../../common/config/main.php', // merged with
    __DIR__ .'/../../common/config/env.php', // merged with
    __DIR__ .'/../../common/config/local.php' // merged with
))->run();

Yiinitializr\Cli namespace

This namespace brings utilities to interact with the terminal or ‘cli’. A free beer goes to mr nramenta for them.

Yiinitializr\Cli\Console

The Console class helps you to display information to the console. You probably, think that it as easy as to ‘echo’ from any of your Command components that are runed by the Yiic command and is true, but this class comes with some magic:

Color

Console::output('this is %rcolored%n and %Bstyled%n');

Prompt

$db_host = Console::prompt('database host', ['default' => 'localhost']);

Selection

$opt = Console::select('Do you love Yii?',
    ['y' => 'yes', 'n' => 'no', 'a' => 'all']
);

Confirm

$sure = Console::confirm('are you sure?');

Work

<?php
Console::stdout('Working ... ');
Console::work(function($socket) { // $socket is optional, defaults to a spinner
    $n = 100;
    for ($i = 1; $i <= $n; $i++) {
        // do whatever it is you need to do
        socket_write($socket, "[$i/$n]\n");
        sleep(1); // sleep is good for you
    }
});
Console::stdout("%g[DONE]%n\n");

Yiinitializr\Cli\Daemon

The Daemon class provides helpers for starting and killing daemonized processes.

<?php
use Yiinitializr\Cli\Daemon;
if (Daemon::isRunning('/path/to/process.pid')) {
    echo "daemon is running.\n";
} else {
    echo "daemon is not running.\n";
}

Yiinitializr\Composer namespace

I should just call this namespace Tobias Schmunk as he was the master guru behind this class, the only thing I did was to read the e-book of Composer and studied every single piece of his fabulous Phundament application boilerplate. To modify the class to become of more general usage out of Phundament has no much credit.

Here, we find the Callback class, a super useful class that will allow you to execute commands prior, post Composer extensions installations or updates. It makes use of the scripts configuration feature and even though for the current templates found at Yiinitializr Site the only thing it does is to call Yiic migrate commands but I am sure that you are already thinking of its possibilities.

Yiinitializr\Helpers namespace

Yiinitializer\Helpers\ArrayX

This class includes cool functions to work with arrays. It contains one cloned from CMap, the mergeArray function, as we require this method in order to combine the different configuration files before the Yii application is even included. A clear example of it you find it on Yiinitializr/config/console, which is the file that where you set the configuration of your console application to run Composer callbacks. It has also

Yiinitializr\Helpers\Config

It reads the configuration file and provides an interface to access the settings. It also, when working with different environments, writes the “env.lock” file. By creating this file, it tells the Initializr helper class to not recreate the env.php configuration file of the environment selected. If anybody wishes to recreate them, in order to make use of other environment configuration file (ie. stage vs local), the coder just needs to delete the “env.lock” file from the Yiinitializr/config folder.

The configuration file

As with Yii, you need to go through a bit of configuration settings if you wish to handle your project structure initializing setup with Yiinitializr. But don’t worry, is not going to be too hard, the following is an example configuration file:

\\ where am i?
$dirname = dirname(__FILE__);
\\ where is the application folder?
$app = $dirname . '/../../..';
\\ where is the root?
$root = $app . '/..';
return array(
    // yii configurations
    'yii' => array(
        // where is the path of the yii framework?
        // On this example we have installed yii with composer
        // and as it is used after composer installation, we
        // can safely point to the vendor folder.
        'path' => $app . '/lib/vendor/yiisoft/yii/framework'
    ),
    // yiinitializr specific settings
    'yiinitializr' => array(
        // config folders
        'config' => array(
            // we just need the console settings
            // On this example, and due that I used environments
            // i created a custom console.php app for
            // Yiinitializr\Composer\Callbak class
            'console' => $dirname . '/console.php'
        ),
        // application structure settings
        'app' => array(
            // where is the root?
            'root' => $root,
            // directories setup
            'directories' => array(
                // where are the different configuration files settings?
                'config' => array(
                    // 'key' is the configuration name (see above init example)
                    'main' => $app . '/config',
                    'console' => $app . '/config',
                    'test' => $app . '/config'
                ),
                // where are my runtime folders?
                'runtime' => array(
                    // heads up! only the folder location as "/config" will be
                    // appended
                    $app
                ),
                'assets' => array(
                    // where to write the "assets folders"?
                    $root . '/www'
                )
            ),
            'files' => array(
                // files to merge the main configuration file with
                // initializr will merge it automatically
                'config' => array(
                    'main' => array('env', 'local'),
                    'console' => array('env', 'local'),
                )
            )
        ),
    )
);

Yiinitializr\Helpers\Initializer

This class requires a little bit more attention and I hope you take a bit of time reading its code to truly understand what it does. Improving this class, can make our lives easier with Yii and I explain why:

  1. It tries to solve the problem with YII_DEBUG dynamically (no need to hardcode true|false on your index.php bootstrap file) – check the setOptions function.
  2. It creates all necessary read+write folders like runtime and assets (Yiinitializr works in conjunction with Composer but I am pretty sure some of you are already thinking on why is not Yii creating those folders when they are not found? Initializer class may provide the solution: if it doesn’t exist, build it don’t fail on error!)
  3. Automatically merges different configuration files that you may have for the different type of applications – check the config function.

Final Notes

We truly hope at 2amigOS! that you find this library as useful as it is for us. We do not expect that this procedure should be implemented at Yii‘s core but some of the features included in this small library are certainly something to consider on its future releases. Happy Yii coding!

References


9 comments

  1. Claudio Ferrari   •  

    Hi Antonio,

    first of all, thanks again for sharing, well done, guys !

    just a simple question: everything has gone well (installation, backend, fronted, etc.) but if I add a widget in, for example, frontend/views/site/index.php I get this error:

    Fatal error: Call to a member function getApi() on a non-object in /Library/WebServer/Documents/advanced/common/lib/vendor/2amigos/yiiwheels/behaviors/WhPlugin.php on line 43

    What is wrong ?

  2. Antonio Ramirez   •     Author

    Claudio… Have you tried with latest? That bug was already fixed.

  3. Pedro Plowman   •  

    Hola Antonio

    I love the promise of Yiinitializr but I’m not getting it to work. I’ve just posted an issue on the GitHub page for Yiinitializr-advanced…

    Over multiple attempts at setting up a Yiinitializr-advanced project I’m getting persistent 403 errors on the backend site. After running composer install I set permissions using…

    yiinitializr$ chmod -R 755 ./
    yiinitializr$ chmod 777 */controllers
    yiinitializr$ chmod 777 */models
    yiinitializr$ chmod 777 */modules
    yiinitializr$ chmod 777 */runtime
    yiinitializr$ chmod 777 */views
    yiinitializr$ chmod 777 */www/assets

    I can reach both the frontend & api hosts in my browser & the host for my backend works if I set it to any other web folder.

  4. Antonio Ramirez   •     Author

    Have you run the “composer install” ? with that you dont need to do setup the permissions for the folders you shown (controllers, models, modules yes if you are using “gii”.

    You need to setup a “vhost” for each of the applications to run properly, so you access each app separately. This project doesnt work with “http://localhost/yourapp/frontend/www” type of thing.

  5. Pedro Plowman   •  

    Yes I have run composer install, the full stack of commands I run is…

    yiinitializr$ composer install
    yiinitializr$ chmod -R 755 ./
    yiinitializr$ chmod 777 */controllers
    yiinitializr$ chmod 777 */models
    yiinitializr$ chmod 777 */modules
    yiinitializr$ chmod 777 */runtime
    yiinitializr$ chmod 777 */views
    yiinitializr$ chmod 777 */www/assets

    With chmod -R 755 ./ being because I gor a 403 error on my first attempt on all 3 faces of Yiinitializr. All of the chmod 777 commands are from my usual practice when setting up Yii to ensure that folders which need to be writable by the server are.

    All of my web projects have local vhosts created using Mac OS X Server & for Yiinitializr they are…

    http://yiinitializr.local directed to /WWW/yiinitializr/frontend/www
    http://hq.yiinitializr.local directed to /WWW/yiinitializr/backend/www &
    http://api.yiinitializr.local directed to /WWW/yiinitializr/api/www.

    Both http://yiinitializr.local & http://api.yiinitializr.local work. Because http://api.yiinitializr.local returns an empty document at this stage I temporarily substituted a phpinfo document as index.php & that displayed correctly (& it’s PHP 5.4.24 BTW). If I set http://hq.yiinitializr.local to /WWW/yiinitializr/frontend/www or any other valid www folder it works.

    When I found Yiinitializr it looked to be everything I’d hoped for because the supporting web stuff for a mobile project I’m developing (as a team of one) requires a frontend, backend & API. Until I found Yiinitializr I thought ‘d be building them as 3 Yii sites all working from the same database.

  6. Antonio Ramirez   •     Author

    Hey Pedro, sorry for the issues with the permissions. Nevertheless, the API calls require that you send a header with HTTP_API key and also a signature parameter, otherwise it wont work. I will send you a js file that I’ve used on my mobile apps to access the Yiinitializr API app.

  7. Rich Webster   •  

    Hi Antonio….

    This is an impressive setup, thanks.

    I’m dying to have these elements, but since this is derived from previous work, and I’m new to Yii, some things need to be explained better for a noob… I’ve spent a half day tracking down the explanation of the file hierarchy, where a simple link from from the README.md to http://www.yiiframework.com/wiki/155/the-directory-structure-of-the-yii-project-site would’ve been invaluable… or better yet: copy that over to your docs with the info updated to your system.

    The file hierarchy buries the www files. Above you mention that vhosts must be set up (though that’s not mentioned on the README). There are a lot of files here to look through to deduct a setup that will work… can you explain what has to happen after “composer install” to actually have it become fully functional and how to go from a local dev environment > staging > live? It would be a great addition to the README.

    Thanks!

  8. Antonio Ramirez   •     Author

    Hi Rich,

    Thanks for your compliments… I know there is a lack on documentation but I am terribly busy lately. Apologies.

Add Comment Register



Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>