Running your Yii app and configuring it

December 29th, 2008

Unlike in CakePHP, it is mandatory to use the shell tool (called yiic, similar to CakePHP’s “Bake” script) to start off your application as it creates the workspace architecture (The Yii package does not come with an application bare-bones, only framework code). Yiic generates .htaccess files with rules that forwards user requests to index.php where the application runs (cake does this too). When I checked my index.php file to see what was in it, I was amazed with the possibilities of what I saw.

<?php
// change the following paths if necessary
$yii = 'C:\wamp\www\yiiRepo\framework\yii.php';
$config = dirname(__FILE__) . '/protected/config/main.php';
 
// remove the following line when in production mode
defined('YII_DEBUG') or define('YII_DEBUG',true);
 
require_once($yii);
Yii::createWebApplication($config)->run();

The last two lines are the important ones. In the second-last line, it includes the main Yii class file, so that it can actually run the application as seen in the last line. createWebApplication() accepts one argument: the path to the configuration file for the application. In the configuration file you can configure things such as your database, error and mysql logging, and url routing. The configurations are stored in the form of an array. It’s a much simpler approach than cake’s, which uses a heavy configuration class. Personally I am liking Yii’s array configuration syntax much better than cake’s (I will show you my Yii configuration file in a second).

Since in Yii you define the configuration file used in your index.php file, you can greatly simplify the synchronization between your development and production server – you simply need different index files and separate configuration files. So I thought up a inheritance/tree system for configuration files.

/protected
	/config
		/main.php
		/production.php
		/development.php

Here, the production and development configuration files will simply extent the main configuration file which holds the configurations that are consistent across both production and development servers such as the url routing rules. Possible examples of each file:

protected/config/main.php:

<?php
// This is the main Web application configuration.
return array(
	'basePath' => dirname(__FILE__).DIRECTORY_SEPARATOR.'..',
	'name' => 'My Web Application',
 
	// Tell's Yii is can auto-load model and component classes on-demand (lazy loading)
	'import' => array(
		'application.models.*',
		'application.components.*',
	),
	'preload' => array('log'), //preload the log component right away (eager loading)
 
	// application components
	'components' => array(
		'user' => array(
			// user component settings here (similar to CakePHP's auth component)
		),
		//log class can output errors, mysql quarry summaries, etc.  The specific
		//settings are extended in the production and development config files
		'log' => array(
	        	'class' => 'CLogRouter',
		),
		'urlManager' => array(
			'urlFormat'=>'path',
			'showScriptName' => false,
			'rules' => array(
				// some generic url routes I often use
				'user/register/*' => 'user/create',
				'user/settings/*' => 'user/update',
			),
		),
	),
);

protected/config/development.php:

<?php
//import main configurations
$main = include "main.php";
 
// Development configurations
$development = array(
	'components' => array(
		'db' => array(
			'class' => 'CDbConnection',
			'connectionString' => 'mysql:host=localhost;dbname=yiitestdrive',
			'username' => 'root',
			'password' => '',
		),
		'log' => array(
			'routes' => array(
				//set the log component to show logs on the bottom of the page - similar to CakePHP
				array(
					'class' => 'CWebLogRoute',
					'levels' => 'trace, info, error, warning',
					'categories' => 'system.db.*',
				),
			),
		),
        ),
);
//merge both configurations and return them
return CMap::mergeArray($main, $development);

protected/config/production.php:

<?php
//import main configurations
$main = include "main.php";
 
// Production configurations
$production = array(
	'components' => array(
		'db' => array(
			'class' => 'CDbConnection',
			'connectionString' => 'mysql:host=mysql@example.com;dbname=productionDatabase',
			'username' => 'admin',
			'password '=> 'password123',
		),
		'log' => array(
			'routes' => array(
				// Configures Yii to email all errors and warnings to an email address
				array(
					'class' => 'CEmailLogRoute',
					'levels' => 'error, warning',
					'emails' => 'admin@example.com',
				),
		),
        ),
);
//merge both configurations
return CMap::mergeArray($main, $production);

As you can see, in the main config file we have the consistent settings such as URL routing, and in the production and development files we have inconsistent things such as database settings. Note also in the production config I have errors and warnings sent to an email while in the development config I have all logs outputted at the bottom of the page. Nifty, huh? Now we can set up the index files for the production and development servers like so:

Development index.php file:

<?php
$yii = 'C:\wamp\www\yiiRepo\framework\yii.php';
$config = dirname(__FILE__) . '/protected/config/';
 
// turns debug on
defined('YII_DEBUG') or define('YII_DEBUG',true);
 
require_once($yii);
Yii::createWebApplication($config . 'development.php')->run();

Production index.php file:

<?php
$yii = 'framework/yii.php';
$config = dirname(__FILE__) . '/protected/config/';
 
require_once($yii);
Yii::createWebApplication($config . 'production.php')->run();

Now you can easily set different settings for production and development set-ups without redundancy. Enjoy.

UPDATE: Qiang wrote his own version of this method in the Yii Cookbook here. He recommends you merge the configurations with CMap::mergeArray() instead of array_merge_recursive(). I have changed this article to use CMap also. CMap::mergeArray() is a helper method that comes from the Yii core.

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Technorati
  • Reddit
  • RSS
  • Twitter

Categories: Yii

Leave a comment

Comments Feed63 Comments

  1. Qiang

    Very nice trick and writing! You should share this with the Yii community.

  2. Jonah

    Thanks Qiang! Glad to have your approval (as a Yii developer). But I am in fact sharing this with the Yii community, aren’t I, by blogging it? Do you want me to put it on the forum? I wouldn’t mind advertising my blog on the forum if that’s ok.

  3. Al

    Nice job. I’m in the learning curve of Yii myself. If you place the framework directory relative to application, you could set the $yii variable with a dirname as well.

  4. Boston

    Thanks for the write ups so far. I’m exploring frameworks right now and trying to decide on one to use. I don’t really have any experience with them, so I’m looking forward to more of your thoughts on Yii.

  5. thom

    Excellent information!

  6. yugene

    wow. thanks)

  7. Salvatore Miceli

    Thanks, excellent tips!

  8. balrok

    was very helpful for me, just a few corrections:
    you forgot the semicolon behind CMap::mergeArray(..)
    and ‘CEmailLogRoute’ requires ‘emails’=>’blabla’ as argument not ‘email’

  9. Jonah

    Fixed, thanks!

  10. sendipad

    Excellent Tutorial, I just started read in the web world about Yii and after i saw ur two excellent posts i am gonna stick with yii after a month of looking for the best php framework.

    I hope u provide us with excellent and nice step by step tutorial.

    Thanks

  11. Andrey Viana

    Hi, I propose something like that on the index.php (main) file:

    [code]
    run();
    [/code]

    So just change APPLICATION_ENV constant to your needs :-)

  12. Andrey Viana

    I dont know why, but my code above dont apears, so I create a pastie: http://pastie.org/1522272

  13. perochak

    Great.
    Thanks

  14. Jymeybtp

    I’m a member of a gym wide6
    49971

  15. Insattisk

    OPLURUZZRO uggs france CVCWCGQYAG http://www.ne-ns.com

  16. trend micro titanium antivirus

    zbqtbqiq.uipvhiut, titanium trend micro, PMWMHaU, [url=http://1antiviruszone.com/]trend micro titanium antivirus 2011 free download[/url], NIoqWGn, http://1antiviruszone.com/ trend micro titanium antivirus 2011 free download, lbpgRzO.

  17. Paul Mitchell Hair Straightener

    pkjfjqiq.uipvhiut, Paul Mitchell Flat Iron, ZIDigyt, [url=http://paulmitchellflatiron.com/]Paul Mitchell Hair Straightener[/url], ZnOCwdB, http://paulmitchellflatiron.com/ Paul Mitchell Hair Straightener, rGxIliM.

  18. Buy Valium

    jpqlkqiq.uipvhiut, Valium without a prescription, brfDXxU, [url=http://www.freespiritparagliding.com/]Generic Valium[/url], VkmTvop, http://www.freespiritparagliding.com/ Valium, delyQZL.

  19. weight loss pills reviews

    euhsoqiq.uipvhiut, diet pills, YwLcokE, [url=http://www.weightlossfortoday.com/]weight loss products[/url], jIlsdxO, http://www.weightlossfortoday.com/ diet pills, PkAKvRY.

  20. House Prices

    iqxptqiq.uipvhiut, House Prices, TjuTiXb, [url=http://sustainable-finance.org/]House Prices[/url], giNRQRs, http://sustainable-finance.org/ House Prices, UfpVfFE.

  21. mlm leads

    qwtrxqiq.uipvhiut, business lead generation, UBJnLTP, [url=http://myleadnetproonline.com/]lead generation[/url], HzDkzkp, http://myleadnetproonline.com/ lead generation, hNPOOjh.

  22. Ribzcgln

    What sort of work do you do? Lolitas Rompl
    qxx

  23. Order ambien sleeping pill

    myrqyqiq.uipvhiut, Purchase ambien no prescription, VjzWLCB, [url=http://www.celebrityhotspot.com/]Buy ambien discount[/url], pzDCklZ, http://www.celebrityhotspot.com/ Buy Ambien, BNxDVew.

  24. Valium online

    epiveqiq.uipvhiut, Purchase valium online, pYRQgbU, [url=http://www.passportvisapros.com/valium.html]Buy online no prescription order valium[/url], SufLrfb, http://www.passportvisapros.com/valium.html Buy online no prescription order valium, mXMZrby.

  25. Hzyfndsr

    Could I ask who’s calling? Lolita Hentai
    8(

  26. Qnjytwbj

    I came here to work Preteen Girls Nn
    475535

  27. Best Dating Sites

    albaoqiq.uipvhiut, Best Dating Sites, xWmSRGH, [url=http://top10bestonlinedatingsites.com]Online Dating Sites[/url], lxPYweE, http://top10bestonlinedatingsites.com Best Online Dating Sites, YZXqHjC.

  28. ZetaClear

    kguqrqiq.uipvhiut, Zetaclear nail fungus treatment, tSqOHgd, [url=http://zetaclear4u.com/]ZetaClear[/url], THsKupM, http://zetaclear4u.com/ ZetaClear, cJZzwtu.

  29. Free mobile porn

    icwemqiq.uipvhiut, Porn videos, ZtioYrp, [url=http://hteps.com/]Hentai porn[/url], lNfCfao, http://hteps.com/ Lolita porn, AzBZinZ.

  30. Bzlezefz

    We’ve got a joint account Freedom Lolita Bbs
    aseo

  31. Xggwumwn

    I’ve been cut off Preteen Sex Stories
    :((

  32. speed up my pc

    vrztsqiq.uipvhiut, speed up my pc, XvgDRAI, [url=http://www.speedupmypcfree.net/]speed up my computer[/url], PjPmUUN, http://www.speedupmypcfree.net/ speed up my pc, VQxOBpC.

  33. Eudpwjfu

    A pension scheme death wish rape pictures >:-((( lesbian hardcore porn and rape 2670 brutal rape sex >:]]] strabon rape 67627 rape in the holocaust obui karate girls vs rape team 98797 rape scene young actress 949434 statutory rape definition :-( cartoon rape pron :[ abduction rape movies =DD

  34. Joireecic

    WJUXNXorAINODNT cheap uggs BTDORKndRXLRJOK http://cheapuggsuksale.webeden.co.uk

  35. grielieri

    SFGPIGTKHF cheap tiffany jewelry LGBFIBOKBA http://www.brooklynsunsetweb.com

  36. Ljyzgcxk

    It’s a bad line hentei rape fantasy %DD dad son sex rape incest 58106 free rape top 100 >:] teen date rape research 918333 forced feminization forced feminization stories :[ rape incest 2 yafm stargirl rape rpg hjqx her ass rape 83255 fantsy rape stories =-) tennessee stautory rape %-)))

  37. Stickam teen

    evyhiqiq.uipvhiut, Stickam caps bate, SWmMNAd, [url=http://funadultcams.com/]Jailbait stickam capture[/url], UkaXyBD, http://funadultcams.com/ Stickam tits, FaBcBGJ.

  38. Tslztqvo

    Do you know the number for ? Pthc Lolita Top
    ivte Lolita Preteen Nymphets
    4119 Bbs Preteen Models
    %[

  39. Ssguunof

    I’m not interested in football Top Lolita
    ourxl Preteen Nonude
    %]]] Lolita Art
    404106

  40. Jodpitnj

    Have you got a current driving licence? Preteen Bikini Models
    >:[[ Preteen Models Bbs
    pdw Lolita Incest
    :))

  41. Dlmlwxqq

    Whereabouts are you from? Preteen Vagina
    jote Preteens Nude
    :-((( Preteen Lolita Pussy
    %]]]

  42. Rjjcglox

    I was made redundant two months ago Gothic Lolita
    135681 Lolita Boys
    558 Bbs Lolita
    :P

  43. Rlzegzdp

    I’d like to take the job Preteen Lolita Top
    >:PP Lolita Forum
    048 Lolitas Top 100
    eio

  44. Nkktfkpe

    It’s serious Underage Lolita Pic
    45607 Preteen Nude Pics
    406 Preteen Underage Nude
    414385

  45. Klnesqub

    We used to work together Lolita Underage Nude
    849 Lolita Cumshots
    :-))) Preteen Lolitas
    >:(

  46. Bbtmluhm

    What sort of music do you listen to? lolitas nudes pics foto 004 lolita sex bbs guestbook 824915 14 lolita free 968 lolita underage 12 akyc girl hot sex lolita roapwz lolitas vodeo 1487 lolitas messageboard 7941 lolitas lesbian free 063 nude kids lolitas %-DD top lolitas link >:[

  47. Navumshh

    I’m unemployed 101 lolita sex sites =-DDD child pedo lolitas :]]] preteen lolita fuck kids igho lolita blog forum 6203 lolita nude teen jmgfbu lolita video clip llyjab lolita porn pedo preteen rtgn preteen toplist nude lolita lxpkmr wild lolita
    oftcm sick russian lolitas ejcsu

  48. Zfxvsril

    Have you seen any good films recently? preteen models bbs lolita =-O small lolita vagina ewlnc preteen lolita xxx free 51245 cp lolita movie
    vrrpi shylolita top dark bxb xxx russian lolitas pedo %]] lolita bbs kds video 8-[ lolita eat cum aroud bbs dragon lolita 831311 gallerie virgin porn lolita 337

  49. Jwbkoims

    Do you need a work permit? fucking kid russian fzvenn

  50. kcsdysvfyq

    xilouqiq.uipvhiut, fqdzandmsm

  51. Juegos juegos de carros

    txodtqiq.uipvhiut, Viagra, WMbeKDI, Free ares 2 0 9 download mac software wareseeker search, lIwxSut, Meninas, BAEDtup, Free online blackjack games, eDTzOIj, Torrent Downloads, hPhnEAY, Juegos de carros de carrera y auto bus, LEaWCJq.

  52. Zinsen Tagesgeld

    gcxtxqiq.uipvhiut, Mapquest, JGXYLDg, Life drawing model photos, pvQizxS, sell house quick, SfwSNrO, Created by awstats plugins online pharmacy tramadol, fFyZkHO, african mango australia, sZATfBa, Tagesgeld Zinsen, rUgSFFw.

  53. Ultram clonazepam

    prrbsqiq.uipvhiut, Buy ambien online pharmacy, JEFBFvZ, Where to buy sizegenetics, tmuMbZS, siteground web hosting, aqyxBwp, Buy xenical online no prescription, lZTGXeZ, Ultram clonazepam, fSSgmCN, vps cpanel hosting, BmjFGpd.

  54. How long did it take breast actives users to even out breast sizes

    qgnriqiq.uipvhiut, Breast actives before and after pictures, SjoyvBl.

  55. Euro 2012 Football Cup

    Walt Whitman: “I celebrate myself, And what I assume you shall assume, For every atom belonging to me as good belongs to you.”

  56. Jason

    Yii is an amazing framework. We utilized Yii as the framework for our open source crm application Zurmo (zurmo.org). We love it.

  57. Hqdppumm

    I came here to work sexy preteen 100 5684 french preteen gallery 8-((( preteen uncensored collection 8-DDD preteen toplist thumbnails lgnjr 17 thumbs preteen 942931 preteen ass xxx 9727 preteen top index 861408 girl preteen rape >:))) preteen nude cam =)) models pics preteen :[[[

  58. nfjopdkiwg

    ezyubqiq.uipvhiut, ovihvzbjyn

  59. teeth whitening

    Its such as you read my thoughts! You seem to understand
    a lot about this, like you wrote the e-book in it or something.

    I feel that you simply can do with some percent to power the message
    home a bit, however other than that, that is excellent blog.
    A great read. I’ll certainly be back.

  60. green coffee diet

    Hi, i think that i saw you visited my website so i came to
    “return the favor”.I’m trying to find things to improve my site!I suppose its ok to use some of your ideas!!

  61. driciattadymn

    cheap oakley Reports are always up-to-date no matter where you are26 Can archive, download and run reports day or night 27 System speed is quick 28 Pre-configured defaults29 Have option for patient and appointment data imports30 cheap oakley They don’t involve a good deal of moisture when cleansing them, for that reason foam would serve the function well Make positive to clear any spills and stains on the carpet once you see itThe false fixes for the putting yips have included methods like changing grips, changing finger position, changing putting speed or changing clubs entirely These may provide you a different putting approach, but they will not get rid of your putting yips, and will not allow you to find the yips cureChanging your mechanics or fundamentals is like moving a yard with weed problems The lawnmower will kill the problem at the surface, but the weeds (and the putting yips) will still by lying underneath Think of it this way: if your sink is leaking, you would not use a mop to clean it up before first turning the water up.
    Cheap Oakley Sunglasses The focus of this year will not be on the top two draft picks, but on (arguably) the top 2 players in the league Expect Kobe and Shaq to dominate national headlines as each will set out to prove that they were not the cause of the Lakers collapse in the Finals against the Nets It is a matter of public record that during stretches of the last 2 seasons, that when either Kobe or Shaq would go down with an injury, the Lakers won more with Kobe OUT of the line-up, then when Shaq was out of the lineup Much more, as this chart from will illustratePlus/Minus splits for Shaq-KobePlayerSituationOff48Def48Net48WLShaqwith Kobe1040 93 Discount Oakley Sunglasses ) Medical writing services and9) Animation & simulation technologyJobs in KPOs are more preferred than jobs in BPOs because they promise long term growth in careers and the nature of job is also not so monotonous They relate to knowledge and learning jobs rather than regular copy paste or calling jobs like in BPOs To work in this industry, one needs various skills and abilities like advanced information search; analytical, interpretation and technical skills along with professional and decision-making aptitude.

  62. driciattadymn

    true religion jeans for women Utilizing the correct enter from area agents, which you are able to manage to a considerable degree by environment guidelines, Untapped goldmine can aid to produce productivity improve by automating the actual marketing actions, and therefore streamlining product sales The income process begins along with winning customers Cellular product sales individuals can get into their customer info remotely, along with the GoldSync component of GoldMine will certainly synchronize the info through the system, regardless of person dispersal A income manager may use this information to create substantial studies, which could highlight the most efficient prospects and prospective clients These types of leads might be specific within an marketing campaign to enhance the chance associated with elevated income cheap true religion jeans This analysis has been prepared to provide business insights for management consultants, industry analysts, market research organizations, investors, and corporate advisors It will help them understand the needs of the business as a whole, its strategic position, and identification of initiatives that will allow them in informed decision-making It involves drilling down into a companys corporate family structure, and tracking relevant news stories and trade articles, revenue patterns and growth historyThe research delivers wide knowledge to clients for building their understanding about the profitability and long-term financial strength of the Company It also facilitates intelligence on a firm’s core competencies and areas where it can capitalize to sustain its competitiveness.
    true religion jeans men   Next, the professional should know if you should lead so when to handle the girls This can help the supervisor to avoid space between employees as well as management as well as achieve the objective with no issues   Conversation plays a highly effective in team development and top a gorup Great communication enables the top to share information and also the objective from the organization necessary to be given to towards the workers Therefore , the best choice is needed to create business communication ability together true religion jeans sale Its good enough to start off with Register for a free account here: ://www For those new to the SEO industry, you might wonder what backlinks are and how essential they are for the success of websites In short, a Backlink indicates a link from another site to your website These are also known as inbound links and their number indicates the popularity of the website Backlinks are considered as votes by search engines: more the number of votes (backlinks) your website has, and based on the importance of websites linking back to yours, your site is assigned a trust rankBacklinks today are an important part of the SEO process because when you build quality backlinks, your website stands a higher chance of getting indexed faster by the search engines.

  63. Emily

    Is there ? 500mg amoxicillin trihydrate For details, see the installation manual for “Utility Software” and “manual.pdf” in the CD-

Leave a comment

Feed

http://php-thoughts.cubedwater.com / Running your Yii app and configuring it