autosave message to file when developing using Yii::t()

When you develop an international site using CPhpMessageSource, it’s offen to copy and paste messages from view into message files.

To cut off this step, do following:

  1. Create file protected/components/MessageBehavior.php:



<?php

class MessageBehavior extends CBehavior {

	public function events() {

		//we don't want to decrease the performance of server

		if (YII_DEBUG) {

			return array(

				'onMissingTranslation'=>'missingTranslation',

			);

		}

		

		return array();

	}

	

	public function missingTranslation($event) {

		$file = $event->sender->basePath.DIRECTORY_SEPARATOR.$event->language.DIRECTORY_SEPARATOR.$event->category.'.php';

		$message = str_replace("'", "\'",$event->message);

		

		if (is_file($file)) {

			$contents = file_get_contents($file);

			$contents = preg_replace("/\)\s*;/", "\t'{$message}'=>'{$message}',\n);", $contents);

		}

		else {

			$contents = "<?php\nreturn array(\n\t'{$message}'=>'{$message}',\n);";

		}

		

		$fp = @fopen($file, 'w');

		

		if ($fp) {

			fwrite($fp, $contents);

			fclose($fp);

		}

	}

}

  1. In the config file main.php, define message component (using behavior) as follows:

return array(

	......

	'language'=>'en',

	'components'=>array(

		......

		'messages'=>array(

			'class'=>'CPhpMessageSource',

			'behaviors'=>array(

				'message'=>array(

					'class'=>'application.components.MessageBehavior',

				),

			),

		),

		......

	),

...

);

  1. After all messages are saved into message files, translate the files.

OK, that’s all.

Sorry for my bad English.

Isn’t it easier to run yiic message with overwrite set to true?

Thanks for your reply, I missed [yiic message].

But I think, with my solution you can automatically translate from a language to another using a free translation api like Bing (http_//www.microsoft.com/web/post/using-the-free-bing-translation-apis)

Best regards,

Thanh Nguyen

Right. I didn’t think about automated translation with free API… It might be a nice solution for a preliminary translations.

There is a admin module called Translate on the Extensions site that does what you want using Google translate. You could probably adapt it to use Bing. You create the base message string to be translated in a message source table and the translations are stored as separate records in a message translate table. The process becomes automatic when the source message is changed and the code automatically checks the application for message strings not included in the source table.