Configura el ambiente de tu aplicacion con Yii Enviroment Class

Hola, había tenido muchos problemas la tratar de estar cambiando la configuración de mi aplicación cuando trataba de editarla en mi servidor local, quitar el debug, trace, etc. así es que creé una clase para evitarme todos estos problemas y poder cambiar de entorno con una sola linea de código, espero les funcione en sus proyectos!

Instrucciones:

  1. Crea un nuevo archivo en la carpeta ‘config’ y nombralo ‘enviroment.php’.

  2. Pega el siguiente codigo en el archivo ‘enviroment.php’ que acabas de crear.





<?php

/**

 * This class helps you to config your Yii application

 * enviroment.

 * Any comments please post a message in the forum

 * Enjoy it!

 *

 * @name Enviroment

 * @author Fernando Torres | Marciano Studio

 * @version 1.0

 */

class Enviroment {


    const DEVELOPMENT = 100;

    const TEST        = 200;

    const STAGE       = 300;

    const PRODUCTION  = 400;


    private $_mode = 0;

    private $_debug;

    private $_trace_level;

    private $_config;




    /**

     * Returns the debug mode

     * @return Bool

     */

    public function getDebug() {

        return $this->_debug;

    }


    /**

     * Returns the trace level for YII_TRACE_LEVEL

     * @return int

     */

    public function getTraceLevel() {

        return $this->_trace_level;

    }


    /**

     * Returns the configuration array depending on the mode

     * you choose

     * @return array

     */

    public function getConfig() {

        return $this->_config;

    }




    /**

     * Initilizes the Enviroment class with the given mode

     * @param constant $mode

     */

    function __construct($mode) {

        $this->_mode = $mode;

        $this->setConfig();

    }


    /**

     * Sets the configuration for the choosen enviroment

     * @param constant $mode

     */

    private function setConfig() {

        switch($this->_mode) {

            case self::DEVELOPMENT:

                $this->_config      = array_merge_recursive ($this->_main(), $this->_development());

                $this->_debug       = TRUE;

                $this->_trace_level = 3;

                break;

            case self::TEST:

                $this->_config      = array_merge_recursive ($this->_main(), $this->_test());

                $this->_debug       = FALSE;

                $this->_trace_level = 0;

                break;

            case self::STAGE:

                $this->_config      = array_merge_recursive ($this->_main(), $this->_stage());

                $this->_debug       = TRUE;

                $this->_trace_level = 0;

                break;

            case self::PRODUCTION:

                $this->_config      = array_merge_recursive ($this->_main(), $this->_production());

                $this->_debug       = FALSE;

                $this->_trace_level = 0;

                break;

            default:

                $this->_config      = $this->_main();

                $this->_debug       = TRUE;

                $this->_trace_level = 0;

                break;

        }

    }




    /**

     * Main configuration

     * This is the general configuration that uses all enviroments

     */

    private function _main() {

        return array(


                // Base Path

                'basePath' => dirname(__FILE__).DIRECTORY_SEPARATOR.'..',


                // Project Name

                'name' => 'Project name',


                // Preloading 'log' component

                'preload'=>array('log'),


                // autoloading model and component classes

                'import' => array(

                        'application.models.*',

                        'application.components.*',

                ),


                // Application components

                'components' => array(

                        'user' => array(

                        // enable cookie-based authentication

                                'allowAutoLogin'=>true

                        ),


                        // Error Handler

                        'errorHandler'=>array(

                                    'errorAction'=>'site/error',

                         ),


                        // URLs in path-format

                        'urlManager'=>array(

                                'urlFormat'=>'path',

                                'rules'=>array(

                                        '<controller:\w+>/<id:\d+>'=>'<controller>/view',

                                        '<controller:\w+>/<action:\w+>/<id:\d+>'=>'<controller>/<action>',

                                        '<controller:\w+>/<action:\w+>'=>'<controller>/<action>'

                                ),

                        ),

                ),


                // Application-level parameters

                'params'=>array(

                        'adminEmail'=>'admin@example.com',

                        'enviroment'=> $this->_mode

                )

        );

    }




    /**

     * Development configuration

     * Usage:

     * - Local website

     * - Local DB

     * - Show all details on each error.

     * - Gii module enabled

     */

    private function _development () {


        return array(


                // Modules

                'modules'=>array(

                        'gii'=>array(

                                'class'=>'system.gii.GiiModule',

                                'password'=>'your password',

                                'ipFilters'=>array(),

                                'newFileMode'=>0666,

                                'newDirMode'=>0777,

                        ),

                ),


                // Application components

                'components' => array(


                        // Database

                        'db'=>array(

                                'connectionString' => 'Your connection string to your local development server',

                                'emulatePrepare' => false,

                                'username' => 'admin',

                                'password' => 'password',

                                'charset' => 'utf8',

                        ),


                        // Application Log

                        'log'=>array(

                                'class'=>'CLogRouter',

                                'routes'=>array(

                                // Save log messages on file

                                        array(

                                                'class'=>'CFileLogRoute',

                                                'levels'=>'error, warning,trace, info',

                                        ),

                                        // Show log messages on web pages

                                        array(

                                                'class'=>'CWebLogRoute',

                                                'levels'=>'error, warning, trace, info',

                                        ),


                                ),

                        ),

                ),

        );

    }




    /**

     * Test configuration

     * Usage:

     * - Local website

     * - Local DB

     * - Standard production error pages (404,500, etc.)

     * @var array

     */

    private function _test() {

        return array(


                // Application components

                'components' => array(


                        // Database

                        'db'=>array(

                                'connectionString' => 'Your connection string to your local testing server',

                                'emulatePrepare' => false,

                                'username' => 'admin',

                                'password' => 'password',

                                'charset' => 'utf8',

                        ),




                        // Fixture Manager for testing

                        'fixture'=>array(

                                'class'=>'system.test.CDbFixtureManager',

                        ),


                        // Application Log

                        'log'=>array(

                                'class'=>'CLogRouter',

                                'routes'=>array(

                                        array(

                                                'class'=>'CFileLogRoute',

                                                'levels'=>'error, warning,trace, info',

                                        ),


                                        // Show log messages on web pages

                                        array(

                                                'class'=>'CWebLogRoute',

                                                'levels'=>'error, warning',

                                        ),

                                ),

                        ),

                ),

        );

    }


    /**

     * Stage configuration

     * Usage:

     * - Online website

     * - Production DB

     * - All details on error

     */

    private function _stage() {

        return array(


                // Application components

                'components' => array(

                // Database

                        'db'=>array(

                                'connectionString' => 'Your connection string to your production server',

                                'emulatePrepare' => false,

                                'username' => 'admin',

                                'password' => 'password',

                                'charset' => 'utf8',

                        ),


                        // Application Log

                        'log'=>array(

                                'class'=>'CLogRouter',

                                'routes'=>array(

                                        array(

                                                'class'=>'CFileLogRoute',

                                                'levels'=>'error, warning, trace, info',

                                        ),


                                ),

                        ),

                ),

        );

    }


    /**

     * Production configuration

     * Usage:

     * - online website

     * - Production DB

     * - Standard production error pages (404,500, etc.)

     */

    private function _production() {

        return array(


                // Application components

                'components' => array(


                        // Database

                        'db'=>array(

                                'connectionString' => 'Your connection string to your production server',

                                'emulatePrepare' => false,

                                'username' => 'admin',

                                'password' => 'password',

                                'charset' => 'utf8',

                        ),




                        // Application Log

                        'log'=>array(

                                'class'=>'CLogRouter',

                                'routes'=>array(

                                        array(

                                                'class'=>'CFileLogRoute',

                                                'levels'=>'error, warning',

                                        ),


                                        // Send errors via email to the system admin

                                        array(

                                                'class'=>'CEmailLogRoute',

                                                'levels'=>'error, warning',

                                                'emails'=>'admin@example.com',

                                        ),

                                ),

                        ),

                ),

        );

    }

}// END Enviroment Class










  1. Cambia los valores para cada entorno, por default lo tengo configurado a mi gusto, pero lo puedes cambiar a tu gusto:

    • DEVELOPMENT

    • TEST

    • STAGE

    • PRODUCTION

  2. Abre el archivo index.php que se encuentra en el root de tu aplicacion y cambia todo el código por el siguiente:





// Change the following paths if necessary

require_once(dirname(__FILE__).'/protected/config/enviroment.php');

$enviroment = new Enviroment(Enviroment::DEVELOPMENT) ;


$yii = dirname(__FILE__).'/../../framework/yii.php';


defined('YII_DEBUG') or define('YII_DEBUG',$enviroment->getDebug());

defined('YII_TRACE_LEVEL') or define('YII_TRACE_LEVEL', $enviroment->getTraceLevel());


require_once($yii);

Yii::createWebApplication($enviroment->getConfig())->run();




5.Para cambiar el entorno solamente debes de modificar una linea de código, ejemplo:




//For development

$enviroment = new Enviroment(Enviroment::DEVELOPMENT); 


//For test

$enviroment = new Enviroment(Enviroment::TEST); 


//For stage

$enviroment = new Enviroment(Enviroment::STAGE); 


//For production

$enviroment = new Enviroment(Enviroment::PRODUCTION);  



  1. Tambien puedes consultar en que entorno te encuentras trabajando dentro de tu aplicación, para eso utiliza el siguiente código:




// Si tenemos, por ejemplo el entorno DEVELOPMENT habilitado, nos regresara la siguiente linea el código '100'

$currentEnviroment = Yii::app()->getParams('enviroment');


//Ejemplo

if($currentEnviroment == Enviroment::DEVELOPMENT){

   //Tu código aqui

}else{

   //Tu código aqui

}






  1. Disfruten! ;D

Muy buena técnica!!! Lo vas a poner en el cookbook?

Estaria bueno asi los demás miembros de la comunidad (que no entren al foro en español) tambien podrían beneficiarse con esta técnica!

Muchas gracias por tu comentario, ya hice un post en la seccion de "Tips, Snippets and Tutorials", pero en un rato más lo subo tambien al Cookbook de Yii!

Sí, me di cuenta de que pusiste el post en ingles en la seccion de “Tips, Snippets and Tutorials” después de postear mi respuesta!!! LOL :P

Listo, el articulo ya está en el Cookbook de Yii, pueden consultarlo en el siguiente enlace(en ingles):

Use different enviroments (developmnet, production, etc) in your app with EASY Enviroment Class