Question

I am building an application using zend framework.

The question is, how to use the same controller logic of the Zend_Rest_Controller within a non-REST app.

For instance, let's assume twitter was written with Zend Framework. They would probably use the Zend_Rest_controller and Route for their API. However, what would they use for their website (which obviously use the same API logic)? Would they write an entire new application that simply fire REST request? Isn't that overload.

[EDIT]
If web app calls API through some http_client class to get the data, that makes another request to server (it causes performance degrade and slow down the response). I don't want to make another request and want to use the same business logic which is in API.

Thanks,
Venu

Was it helpful?

Solution

New Answer:

I have come up with a pattern that seems to work well. It solves all of your concerns: Here is a scaled down version of what I came up with:

First we need our own controller. This conroller will have a service where by it proxies any action request to the service, if they are not defined:

abstract class App_Rest_Controller extends Zend_Controller_Action
{
    /** 
     * @var App_Rest_Service_Abstract
     */
    protected $_service;

    public function __call($methodName, $args)
    {
        if ('Action' == substr($methodName, -6)) {
            $action = substr($methodName, 0, strlen($methodName) - 6);
            return $this->_service()->$action();
        }

        return parent::__call($methodName, $args);
    }
}

Now its time for the service. We extend Action Helper Abstract so that:

  1. we have direct access to the request object
  2. we can easily call up the service from any controller

This will act a go between for the the application and the actual storage of the data.

abstract class App_Rest_Service_Abstract extends Zend_Controller_Action_Helper_Abstract
{
    /*
     * @var App_Rest_Storage_Interface
     */
    protected $_storage;
    public function __call($methodName, $args)
    {
        if (!method_exists($this->getStorage(), $methodName)) {
            throw new App_Rest_Service_Exception(sprintf('The storage does not have the method "%s"', $methodName));
        }

        switch ($methodName) {
            case 'get':
            case 'put':
            case 'delete':
                //if id param isnot set, throw an exception
                if (FALSE === ($id = $this->getRequest()->getParam('id', FALSE))) {
                    throw new  App_Rest_Service_Exception(sprintf('Method "%s" expects an id param, none provided', $methodName));
                }
                $iterator = $this->getStorage()->$methodName($id, $this->getRequest()->getParams());
                break;
            case 'index':
            case 'post':
            default:
                //if index, post or not a tradition RESTful request, the function must expect the first and only argument to be an array
                $iterator =  $this->getStorage()->$methodName($this->getRequest()->getParams());
                break;
        }


        return $this->_getResult($iterator);
    }

    protected function _getResult($iterator)
{ /*
       * write your own, in my case i make a paginator and then
       *  either return it or send data via the json helper
       * 
      /*
}

Now for the interface. This will do the actual work of storing, modifying and returning data. The beauty of using it as an interface is that you can easily implement it no matter what you use for the model layer. I created an abstract Storage that simply has a Zend_Form (for validation) and a Zend_Db_Table for the actual data. but you could also implement it on any object.

interface App_Rest_Storage_Interface extends Zend_Validate_Interface
{
    public function index(array $params = NULL);

    public function get($id, array $params = NULL);

    public function post(array $params);

    public function put($id, array $params);

    public function delete($id, array $params);

}

Now operation anywhere within your site. Suppose you have an "Customers" service. Inside any controller its as simple as

$customer = $this->_helper->helper->customers->get(1);

anywhere else (say a view helper for example):

Zend_Controller_Action_HelperBroker::getStaticHelper('customers')->get(1)

I hope this helps. It is working well for me.

OTHER TIPS

Disclaimer: I've never done this, I don't know how feasible it is.

Since Zend_Rest_Controller extends Zend_Controller_Action with now real rest specific logic except for a few abstract methods, you could just have your website controllers extend the Rest controller. Example:

class Web_IndexController extends Rest_IndexController
{
    public function IndexAction() {
        //do whatever your rest contrller would do
        $result = parent::indexAction();
        //add website specific specific logic here
    }
}

If your rest controller's actions are returning values, such as db objects or arrays based upon what happened, you could then use the returned data to do web site-specific logic.

One thing to think about, if you are using the json action helper to return values for your rest api, you should build in a controller property to suppress the sending and exiting. Example:

class Rest_IndexController extends Zend_Rest_Controller
{

    protected $_sendJson = TRUE;
    public function IndexAction() {
        $this->_helper->json($data, $this->_sendJson);
    }
}

class Web_IndexController extends Rest_IndexController
{
    protected $_sendJson = FALSE;
}

Happy Hacking!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top