Difference between #3 and #2 of How to use Flash, Zend AMF and Yii Framework

unchanged
Title
How to use Flash, Zend AMF and Yii Framework
unchanged
Category
Tutorials
unchanged
Tags
flash, zend, Zend_AMF, AMF
changed
Content
This is a simple demo how to use Zend_AMF with Yii.

### Zend Framework

Download [Zend_AMF](http://framework.zend.com/download/amf) and extract
library/Zend to protected/vendors/Zend

>Info: Zend AMF 1.11.11 has a [nasty
bug](http://framework.zend.com/issues/browse/ZF-11783), so use Zend AMF 1.11.10
or Zend AMF 1.11.12 when it's released.

### EZendAutoloader

Zend Framework class loader for Yii. Create zend/EZendAutoloader.php to
protected/extension:

~~~
[php]
<?php
/**
 * EZendAutoloader
 *
 * @package extensions.zend
 */
class EZendAutoloader extends CApplicationComponent {

	/**
	 * @var string Path to the folder that contains Zend/ and the rest of the ZF
libraries; optional,
     * and only useful if you don't already have the folder listed under
'import' in your config file.
	 */
	public $basePath;

	/**
	 * @var array(string,string,...) An array of custom namespaces the
Zend_Loader_Autoloader should import, eg. 'My_'
	 */
	public $customNamespaces = array();

	/**
	 * Set up Zend_Loader_Autoloader to listen for any autoload requests.
	 */
	public function init()
	{
		$path = $this->basePath;
		if (strlen($path)) {
			// Normalise: strip a trailing "/" if present.
			if (strlen($path) > 1 && $path[strlen($path)-1] == '/') {
				$path = substr($path, 0, strlen($path)-1);
			}

			// Add this library path to PHP's include_path if it's not
			// already there (common for library paths outside of protected/).
			$this->addIncludePath($path);

			// Add a / for ease below.
			$path .= '/';
		}

		// Get Yii out of the way.
		spl_autoload_unregister(array('YiiBase','autoload'));

		// Bring in Zend and set it up to take new autoload events.
		require_once($path.'Zend/Loader/Autoloader.php');
		$autoloader = Zend_Loader_Autoloader::getInstance();

		// Any custom namespaces, eg. 'My_'
		foreach ($this->customNamespaces as $namespace) {
			$autoloader->registerNamespace($namespace);
		}

		// Back to Yii.
		spl_autoload_register(array('YiiBase','autoload'));
	}

	/**
	 * Add include path
	 * @param $path
	 */
	protected function addIncludePath($path)
	{
		if (!file_exists($path) OR (file_exists($path) && filetype($path) !==
'dir')) {
			throw new CException(Yii::t('Include path {path} does not exist.',
array('path'=>$path)));
		}
		$paths = explode(PATH_SEPARATOR, get_include_path());
		if (array_search($path, $paths) === false) {
			array_push($paths, $path);
		}
		set_include_path(implode(PATH_SEPARATOR, $paths));
	}
}
~~~

### Value Objects for Flash

Create a simple Value Object class to protected/components/vo/Application.php

~~~
[php]
<?php
/**
 * Value Object Class for AMF Service
 */
class Application
{
	public $time = '';
	public $datetime = '';
}
~~~

### AMF service

Create a Service class to protected/components/Service.php

~~~
[php]
<?php
/**
 * Service Class for Zend_AMF
 */
class Service
{
	public function getTime()
	{
		return time();
	}

	public function getDatetime()
	{
		return date('Y-m-d H:i:s');
	}

	public function validateEmail($value)
	{
		$validator = new CEmailValidator;
		if(!empty($value) && $validator->validateValue($value))
			return 'ok';

        return 'error';
	}

    public function appInit()
    {
		$a = new Application;
		$a->time = $this->getTime();
		$a->datetime = $this->getDatetime();

		return $a;
	}
}
~~~

### Config

Modify your main config:

~~~
[php]
// Main Web application configuration.

    // Preloading 'log' and 'zend' component
    'preload'=>array(
        'log',
        'zend',
    ),

    // Autoloading model, component, value object and vendor classes
    'import'=>array(
        'application.models.*',
        'application.components.*',
        'application.components.vo.*',
        'application.vendors.*',
    ),

    // Application components

        // Application Log
        'log'=>array(
            'class'=>'CLogRouter',
            'routes'=>array(
                // Save log messages on file
                array(
                    'class'=>'CFileLogRoute',
                    'logFile'=>'web.log',
                    'levels'=>'error, warning, info',
                ),
                array(
                    'class'=>'CFileLogRoute',
                    'logFile'=>'web_trace.log',
                    'levels'=>'trace',
                ),
            ),
        ),

        // Zend autoloader
        'zend'=>array(
            'class'=>'ext.zend.EZendAutoloader',
            // Optional: provide an absolute path to the non-Yii directory
containing the Zend libraries.
           
//'basePath'=>realpath(dirname(__FILE__).'/../../../../private/libs/zf-1.11.10'),
        ),

~~~

### AMF Controller

Create a AmfController (protected/controllers/AmfController.php):

~~~
[php]
<?php

class AmfController extends CController {

	public function actionIndex() {

		$server = new Zend_Amf_Server();

        // It's recommend to disable production mode only when in development.
		$server->setProduction(false);

		// Add our class to Zend AMF Server.
		$server->setClass("Service");

		// Mapping the ActionScript VO to the PHP VO. You don't have to add the
package name.
		$server->setClassMap("VOApplication", "Application");

		$handle = $server->handle();
		echo $handle;
	}
}
~~~

If you are using [Environment
class](https://github.com/janisto/yii-environment/) for Yii, you can use the
'environment' variable to set the production mode.

~~~
[php]

        // Enable production mode if environment is 'production'.
		if (Yii::app()->params['environment'] == 'production') {
			$server->setProduction(true);
		} else {
			$server->setProduction(false);
		}
~~~

### Testing

You can test the AMF gateway with [Pinta](http://code.google.com/p/pinta/) AMF
service test and debug utility.

If you installed the app to http://localhost/flash, then connect to gateway url
http://localhost/flash/amf and call getTime, getDatetime or AppInit method with
pinta.

![Pinta](http://img163.imageshack.us/img163/857/pintayii.png "Pinta")

### Links

* [Zend_AMF
documentation](http://framework.zend.com/manual/en/zend.amf.server.html)
* [Pinta](http://code.google.com/p/pinta/)
* [Demo / source code](https://github.com/janisto/yii-flash-amf-demo)
* [Forum topic for questions and
suggestions](http://www.yiiframework.com/forum/index.php?/topic/26299-discussion-on-the-wiki-article-how-to-use-flash-zend-amf-and-yii-framework/)