0

我创建了一个名为 API 的模块,它为外部客户端提供服务并返回 json 数据。有像http://example.com/api/user/get-by-id/1这样的端点,它返回用户模型的 json 表示。现在我想在我们的网站上使用相同的 api 以避免重复代码。

所以在我的网站上,如果我想获取用户信息,我应该调用api的get-by-id方法(即api模块,用户控制器,getById动作)

当然,我不想通过 http 执行此操作。所以我所追求的是,​​有没有办法调用另一个控制器的动作,捕获响应,并继续原来的动作。

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

1 回答 1

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 编程实践;)

其他选项是创建 Controller 并从而ApiController不是扩展它Zend_Controller_Action,因此您可以使用类似的函数:$this->apiAction()并在当前视图中获取结果。

但最好的方法是将您的 API 代码移动到模型层,并在您的 ApiController(将它们转换为 JSON)和当前的控制器(您可以在其中随意转换它们)中使用将数据作为数组或对象返回的类。

于 2013-08-02T14:55:06.393 回答