phpzend-frameworkzend-rest

More actions in Zend Rest Controller apart from the default actions


I know that REST API can be implemented using Zend_Rest_Controller and it has 5 abstract methods indexAction, getAction, postAction,putAction,deleteAction to perform return, create, update , etc...

My question is, can I have more API fictions with in a controller apart from these default functions to perform various type of operations?.

Eg:

indexAction - returns a list of available books,

searchAction - returns a list of books based on search criterion. (I know it can be done in the indexAction with some parameters but then the code will look more complicated, I need to avoid that)


Solution

  • Yes, you can create custom action methods in your controller. Although you're extending the abstract class Zend_Rest_Controller, as long as you define those 5 abstract methods (the ones you've already mentioned), you're free to customise the rest of your class.

    The only similar method you might look into is the getAction(). This expects a parameter with the name of ID and will retrieve a record based on the primary key.


    You'd probably have to define your routing in a configuration file:

    routes.archive.route = "search/:keyword"
    routes.archive.defaults.controller = books
    routes.archive.defaults.action = search
    routes.archive.defaults.year = "Hamlet"
    routes.archive.reqs.year = "\s+"
    

    And then you need to feed these configuration options into your Router:

    $config = new Zend_Config_Ini('/path/to/config.ini', 'production');
    $router = new Zend_Controller_Router_Rewrite();
    $router->addConfig($config, 'routes');
    

    Read Zend's documentation for a more in-depth tutorial.