How to access CUrlManager in console command?

The generating of sitemap.xml is very time consuming. So that I am writing a console command to generate the sitemap.

The console app (CConsoleApplication) share the same config file of the CWebApplication. However, I found I can not find the url rewrite rules (CUrlManager) in console application. Thus, it is impossible to generate url using Control and Action names.

How to access CUrlManager in console command?

What if you define ‘urlManager’ component in the configuration array to have ‘class’=>‘CUrlManager’?

thanks.

I put the line in the config file like this:


    'urlManager'=>array(

      'class'=>'CUrlManager',



It works partially. the code in the command (CConsoleCommand)


 echo Yii::app()->urlManager->createUrl('post/show', array('post_guid' => $post->post_guid) );



shows the following error:


exception 'CException' with message 'CConsoleApplication does not have a method

named "getRequest".' in D:\www\yii\framework\base\CComponent.php:218


Stack trace:

#0 [internal function]: CComponent->__call('getRequest', Array)

#1 D:\www\yii\framework\web\CUrlManager.php(358): CConsoleApplication->getRequest()

#2 D:\www\yii\framework\web\CUrlManager.php(206): CUrlManager->getBaseUrl()



You can also enable request component by setting its class to CHttpRequest in the config array.

As you can see, console applications are very limited in this regard. You may want to implement this feature in the context of a webapplication.

setting the class to CHttpRequest in the config array does not work.

[color="#8B0000"]I finally found a way to access CUrlManager in console application:[/color]

  1. change Yii code base CUrlManager.php, add a function:



	public function setBaseUrl($baseUrl)

	{

		$this->_baseUrl = $baseUrl;

	}



  1. define ‘urlManager’ component in the configuration array to have ‘class’=>‘CUrlManager’

    'urlManager'=>array(

      'class'=>'CUrlManager',



  1. call setBaseUrl first

 Yii::app()->urlManager->setBaseUrl($site_url);



  1. now, urlManager can be used

 

 echo Yii::app()->urlManager->createUrl('post/show', array('post_guid' => $post->post_guid) );



You can set baseUrl property of CHttpRequest. Then your problem would be solved.

I tried,


Yii::app()->request->setBaseUrl($site_url);

is OK, but


 echo Yii::app()->urlManager->createUrl('post/show', array('post_guid' => $post->post_guid) );

gives the following error:


exception 'CException' with message 'CConsoleApplication does not have a method

named "getRequest".' in D:\www\yii\framework\base\CComponent.php:218


Stack trace:

#0 [internal function]: CComponent->__call('getRequest', Array)

#1 D:\www\yii\framework\web\CUrlManager.php(367): CConsoleApplication->getRequest()

#2 D:\www\yii\framework\web\CUrlManager.php(206): CUrlManager->getBaseUrl()



http://code.google.com/p/yii/issues/detail?id=565