Zend Framework 1.9.2+ Примеры Zend_Rest_Route

С появлением Zend_Rest_Route в Zend Framework 1.9 (и его update в 1.9.2) теперь у нас есть стандартизированное решение RESTful для маршрутизации запросов. По состоянию на август 2009 г. примеров его использования нет, только базовая документация в справочном руководстве.

Хотя это, возможно, намного проще, чем я предполагаю, я надеялся, что более компетентные, чем я, смогут предоставить несколько примеров, иллюстрирующих использование Zend_Rest_Controller в ситуации, когда:

  • Некоторые контроллеры (например, indexController.php) работают нормально.
  • Другие работают как сервисы на основе отдыха (возвращая json)

Появляется помощник действий JSON. теперь полностью автоматизирует и оптимизирует ответ json на запрос, что делает его использование вместе с Zend_Rest_Route идеальной комбинацией.


person Matt Gardner    schedule 27.08.2009    source источник


Ответы (2)


Оказывается, это было довольно просто. Я собрал шаблон Restful Controller, используя Zend_Rest_Controller Abstract. Просто замените возвращаемые значения no_results собственным php-объектом, содержащим данные, которые вы хотите вернуть. Комментарии приветствуются.

<?php
/**
 * Restful Controller
 *
 * @copyright Copyright (c) 2009 ? (http://www.?.com)
 */
class RestfulController extends Zend_Rest_Controller
{

    public function init()
    {
        $config = Zend_Registry::get('config');
        $this->db = Zend_Db::factory($config->resources->db);
        $this->no_results = array('status' => 'NO_RESULTS');
    }

    /**
     * List
     *
     * The index action handles index/list requests; it responds with a
     * list of the requested resources.
     * 
     * @return json
     */
    public function indexAction()
    {
        // do some processing...
        // Send the JSON response:
        $this->_helper->json($this->no_results);
    }
    // 1.9.2 fix
    public function listAction() { return $this->_forward('index'); }

    /**
     * View
     *
     * The get action handles GET requests and receives an 'id' parameter; it 
     * responds with the server resource state of the resource identified
     * by the 'id' value.
     * 
     * @param integer $id
     * @return json
     */
    public function getAction()
    {
        $id = $this->_getParam('id', 0);

        // do some processing...
        // Send the JSON response:
        $this->_helper->json($this->no_results);
    }

    /**
     * Create
     *
     * The post action handles POST requests; it accepts and digests a
     * POSTed resource representation and persists the resource state.
     * 
     * @param integer $id
     * @return json
     */
    public function postAction()
    {
        $id = $this->_getParam('id', 0);
        $my = $this->_getAllParams();

        // do some processing...
        // Send the JSON response:
        $this->_helper->json($this->no_results);
    }

    /**
     * Update
     *
     * The put action handles PUT requests and receives an 'id' parameter; it 
     * updates the server resource state of the resource identified by 
     * the 'id' value.
     * 
     * @param integer $id
     * @return json
     */
    public function putAction()
    {
        $id = $this->_getParam('id', 0);
        $my = $this->_getAllParams();

        // do some processing...
        // Send the JSON response:
        $this->_helper->json($this->no_results);
    }

    /**
     * Delete
     *
     * The delete action handles DELETE requests and receives an 'id' 
     * parameter; it updates the server resource state of the resource
     * identified by the 'id' value.
     * 
     * @param integer $id
     * @return json
     */
    public function deleteAction()
    {
        $id = $this->_getParam('id', 0);

        // do some processing...
        // Send the JSON response:
        $this->_helper->json($this->no_results);
    }
}
person Matt Gardner    schedule 27.08.2009
comment
В итоге исправление не сработало в 1.9.2, вам нужно перенаправить listAction в индекс (обновлено выше). - person Matt Gardner; 28.08.2009
comment
Похоже, это запланировано для версии 1.9.3 (ищите «остальное» в тексте страницы здесь:) framework.zend.com/issues/browse/ZF/fixforversion/10360 - person Matt Gardner; 28.08.2009

отличный пост, но я бы подумал, что Zend_Rest_Controller направит запрос к правильному действию в отношении используемого метода HTTP. Было бы неплохо, если бы POST запрос к http://<app URL>/Restful автоматически _forward к postAction, например.

Я продолжу и предоставлю другую стратегию ниже, но, возможно, я упускаю суть Zend_Rest_Controller ... пожалуйста, прокомментируйте.

Моя стратегия:

class RestfulController extends Zend_Rest_Controller
{

    public function init()
    {
     $this->_helper->viewRenderer->setNoRender();
  $this->_helper->layout->disableLayout();
    }

    public function indexAction()
    {
        if($this->getRequest()->getMethod() === 'POST')
             {return $this->_forward('post');}

        if($this->getRequest()->getMethod() === 'GET')
             {return $this->_forward('get');}

        if($this->getRequest()->getMethod() === 'PUT')
             {return $this->_forward('put');}

        if($this->getRequest()->getMethod() === 'DELETE')
             {return $this->_forward('delete');}

        $this->_helper->json($listMyCustomObjects);

    }
    // 1.9.2 fix
    public function listAction() { return $this->_forward('index'); }

[the rest of the code with action functions]
person Community    schedule 18.09.2009
comment
Еще раз привет, я не собираюсь здесь отвечать на stackoverflow ;0) Я думал, что публикация ответа - единственный способ прокомментировать ваш пост выше. Имейте в виду, что моя панель кода выше выглядит ужасно в формате ответа; 0) - person ; 18.09.2009
comment
Спасибо, чувак :) Забавно, после реализации всего этого мы вернулись к менее спокойной модели. Только что заметил сообщение от руководителя проекта Zend о передовых методах, опубликованное здесь и для других. - person Matt Gardner; 09.11.2009
comment
Zend_Rest_Controller делает все это автоматически. Часть, которую вам не хватает, это инициализация маршрутов REST. - person Andrew; 25.10.2011