Yii Framework Forum: Yii EASY Enviroment Class - Yii Framework Forum

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

Yii EASY Enviroment Class Change your Yii enviroment to development, production, etc. Rate Topic: -----

#1 User is offline   nancoder 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 21
  • Joined: 14-June 10
  • Location:Querétaro, Mx

Posted 16 June 2010 - 01:00 AM

Hi, I was having problems each time I had to test the site or edit something on my local machine, like changing the db connection, change the debug mode to false, the trace level to 0, disable Gii, etc. So I created a class to resolve all my problems, hope to help you in your projects!


Instructions:

1. Create a new file in the config folder, name it 'enviroment.php'.
2. Paste the following code in your 'enviroment.php' file.


<?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








3. Change the configuration for each enviroment:
- DEVELOPMENT
- TEST
- STAGE
- PRODUCTION

4. Open your index.php file an replace all the code with the following code:


// 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. To change the enviroment just you have to change the following code:

//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);  


6. You can check inside your application in what enviroment you are working with the following code:



// This will return the enviroment code number
$currentEnviroment = Yii::app()->getParams()->enviroment;

// Compare if the current enviroment is lower than production
if($currentEnviroment < Enviroment::PRODUCTION){
   //Your code here...
}else{
   //Your code here...
}





7. Enjoy it! ;D
Configure your app enviroment with this Easy Enviroment Class

Follow me on Twitter | LinkedIn
0

#2 User is offline   Mike 

  • Elite Member
  • PipPipPipPipPip
  • Yii
  • Group: Members
  • Posts: 3,013
  • Joined: 06-October 08
  • Location:Upper Palatinate

Posted 16 June 2010 - 02:49 AM

Nice little helper :).

One small suggestion though: I'd use const instead of static for the mode.
0

#3 User is offline   nancoder 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 21
  • Joined: 14-June 10
  • Location:Querétaro, Mx

Posted 16 June 2010 - 02:57 AM

View PostMike, on 16 June 2010 - 02:49 AM, said:

Nice little helper :).

One small suggestion though: I'd use const instead of static for the mode.


Thanks for the suggestion, I just updated the code using constants instead of static vars.
Configure your app enviroment with this Easy Enviroment Class

Follow me on Twitter | LinkedIn
0

#4 User is offline   nancoder 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 21
  • Joined: 14-June 10
  • Location:Querétaro, Mx

Posted 16 June 2010 - 03:20 PM

Article uploaded to the Yii Cookbook, you can check it here:

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

Follow me on Twitter | LinkedIn
0

#5 User is offline   Giovanni D. 

  • Standard Member
  • PipPip
  • Yii
  • Group: Members
  • Posts: 237
  • Joined: 23-December 08
  • Location:London (UK)

Posted 16 June 2010 - 05:07 PM

Hello,
have you also seen this cookbook:
http://www.yiiframew...oc/cookbook/32/

I think it lets you achieve a similar result. Jonah implemented this on the yii playground project too if you want to have a look at it.

bye,
Giovanni.
- Yii Playground: collaborative demo app with small examples to play with.. join us ;) [Fork on github]

- DeploYii: Yii powered task runner and deployment solution

- Social: LinkedIn · Twitter
0

#6 User is offline   samdark 

  • Having fun
  • Yii
  • Group: Yii Dev Team
  • Posts: 3,387
  • Joined: 17-January 09
  • Location:Russia

Posted 16 June 2010 - 05:08 PM

Yes, result will be the same. Code style is a bit different.
Yii 1.1 Application Development Cookbook

Enjoying Yii? Star us at github: 1.1 and 2.0.
0

#7 User is offline   nancoder 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 21
  • Joined: 14-June 10
  • Location:Querétaro, Mx

Posted 16 June 2010 - 07:31 PM

View PostVirtual DarKness, on 16 June 2010 - 05:07 PM, said:

Hello,
have you also seen this cookbook:
http://www.yiiframew...oc/cookbook/32/

I think it lets you achieve a similar result. Jonah implemented this on the yii playground project too if you want to have a look at it.

bye,
Giovanni.



Yes, but the problem that I saw in that approach is that you have to have different files in the config folder, and it doesn't handles the debug and the trace level. Also I added some extra functionality adding a param called 'enviroment' so you can check inside of your app, in wich enviroment are you working. For me is easy just change a constant in one line of code to choose my current enviroment.

I really think that is your choice to use this approach, the other that you mention in your post, or whatever you want, just my 2 cents to help the community of this excelent framework! :)
Configure your app enviroment with this Easy Enviroment Class

Follow me on Twitter | LinkedIn
0

#8 User is offline   Giovanni D. 

  • Standard Member
  • PipPip
  • Yii
  • Group: Members
  • Posts: 237
  • Joined: 23-December 08
  • Location:London (UK)

Posted 17 June 2010 - 12:41 PM

View Postnancoder, on 16 June 2010 - 07:31 PM, said:

I really think that is your choice to use this approach, the other that you mention in your post, or whatever you want, just my 2 cents to help the community of this excelent framework! :)


Yep I agree,
and of course thanks for your cookbook!

Personally I like to have more than one config file but your method has the advantages you highlighted. And it is also true that it will be easy to eventually adapt your code having it reading the config from external files rather than from the methods.. ;)

bye,
Giovanni.
- Yii Playground: collaborative demo app with small examples to play with.. join us ;) [Fork on github]

- DeploYii: Yii powered task runner and deployment solution

- Social: LinkedIn · Twitter
0

#9 User is offline   marcovtwout 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 78
  • Joined: 16-September 10
  • Location:Delft, NL

Posted 08 October 2010 - 09:47 AM

Based on the versions from previous authors, I created my own version of this script.

There is no environment specific code in the Environment.php class, everything is seperated into the config files. Impact on changing the index.php is minimal, but the configuration files need some slight modifications to incorporate the extra attributes. I might also turn them into classes at some point.

Environment is determined by Apache's SetEnv, but this can be easily changed at Environment::getMode()

http://www.yiiframew...kbook/73/#c1952
There is a typo in that code: http://www.yiiframew...kbook/73/#c1958
Yii-Environment Extension - Predefine configurations for use in different environments, like development, testing, staging and production.
NetBeans IDE and Yii projects - Short directions and general tips for managing a Yii application in NetBeans IDE
0

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users