Using Zend AMF with the CodeIgniter PHP framework

CodeIgniter is an very easy to use and fast framework. From all the PHP frameworks out there it is probably the one closest to the way PHP actually works. It doesn't try to be an enterprise level solution, but focuses on practicality, flexibility and ease of use. For example: you can use an MVC setup, but only if you want to. It doesn't force you to follow strict rules. A reason why Rasmus Lerdorf actually likes the framework.

Also you can integrate other libraries. If you are building Flash/Flex applications probably you would want to use the Zend AMF component from the Zend Framework. It has been developed in cooperation with Adobe to create web services that can use the AMF data exchange format.

First you have to create an autoloader for the Zend Framework to easily access Zend components. Assuming you put the Zend Framework in the system/libraries/Zend folder, create system/application/libraries/zend.php:

<?php if( !defined('BASEPATH')) exit('No direct script access allowed');
class Zend {
  public function __construct() {
    ini_set('include_path',ini_get('include_path').PATH_SEPARATOR.APPPATH.'libraries/');
    require('Zend/Loader/Autoloader.php');
    spl_autoload_register(array('Zend_Loader_Autoloader','autoload'));
  }
}

After this you can create a web service by creating the appropriate controller:

class Items extends Controller {
  public function __construct() {
    parent::Controller();

    $this->load->library('zend');
  }

  public function index() {
    $server = new Zend_Amf_Server();
    $server->setClass(__CLASS__);
    echo $server->handle();
  }

  public function getData() {
    return array(1,2,3,'...');
  }

  public function getItem($id) {
    $this->load->model('Itemmodel');
    return $this->Itemmodel->getItem($id);
  }
}

Be aware that you have to load any model from inside the method you are calling. It cannot loaded from the constructor, because this will create a conflict with the Zend AMF instance. Which I found out the hard way.