2013-08-02 31 views
0

我創建了一個名爲API的模塊,它爲外部客戶端提供服務並返回json數據。有像http://example.com/api/user/get-by-id/1這樣的端點返回用戶模型的json表示。現在我想在我們的網站中使用相同的API,以避免重複的代碼。內部使用API​​模塊(ZF1)

所以在我的網站,如果我想獲得用戶信息,我應該叫API的get-ID別方法(這是API模塊,用戶控制器,getById動作)

當然我不想通過http來做到這一點。所以我所追求的是,​​有沒有辦法調用另一個控制器的動作,捕獲響應,並繼續執行原始動作。

<?php 
Class IndexController { 
     public function indexAction() 
     { 
      $user = $this->apiCall(array('userid' => 1)); // This is what I am trying to do. 
     } 
} 

回答

0

Zend中的控制器並沒有設計成這樣做。

你可以嘗試這樣的事情:

$request = new Zend_Controller_Request_Simple(); 
    $request->setParam('id', 55); //param to you API 
    $ApiController = new Api_ApiController($request, new Zend_Controller_Response_Http()); 
    $ApiController->apiAction(); //your API Action 
    $yourResultHere = $ApiController->view->result; //get result from View (this is data send to view, not rendered result) 

但是,這不是很好的Zend的編程習慣;)

其他選項是創建控制器和ApiController而不是Zend_Controller_Action擴展它,這樣的話你可以使用像這樣的函數:$this->apiAction()並在當前視圖中獲得您的結果。

但最好的方法是將您的API代碼移動到Model層,並使用在您的ApiController(將它們轉換爲JSON)和您當前的Controller(您可以隨意轉換它們的地方)中將數據作爲數組或對象返回的數據或對象。 。