针对在 ZF 上创建的网站的简单 REST API 实现

我有一个存储库存的网站,我需要创建一个 REST API,因为我必须放置 Web 组件并向其传递数据。通信将由智威汤逊 (JWT) 保障。我找到了一个非常简单的解决方案zf3-rest-api但我无法实现它,因为我有一些奇怪的文件结构(我没有modules.config.php等)我担心它不是 ZF3 甚至不是 ZF2。我可以编写自定义解决方案,但我不知道应该将代码放在哪里(抱歉我是前端开发人员)?在模块中?以及如何处理路由?这样我就可以通过http://example.com/api/?来参考它

https://img1.sycdn.imooc.com/653397d500012e0204421224.jpg


慕沐林林
浏览 105回答 1
1回答

一只甜甜圈

这是一个 ZF1 应用程序树,ZF1 有其 REST 实现。假设您将其称为“MyRestfulController”。那么你必须注册你的休息路线,你可以在你的 Bootstrap.php 中完成protected function _initRestRoute(){    $frontController = $this->bootstrap('frontController')->getResource("frontController");    $restRouteUL = new Zend_Rest_Route($frontController, array(), [        'default' => [            'my-restful'        ]    ]);    $frontController->getRouter()->addRoute('rest', $restRouteUL);}或者如果您不需要休息,而只是返回一些 JSON 的 API,您可以跳过 Restful 部分并禁用控制器中的布局(因此不扩展 Zend_Rest_Controller ),覆盖“init()”方法    public function init(){    parent::init();    $this->_helper->layout->disableLayout();    $this->_helper->viewRenderer->setNoRender();    $this->getResponse()->setHeader("Content-type", "text/json");        /**     * This is important for the helper not to exit the dispatch loop     */    $this->_helper->json->suppressExit = true;}那么在你的行动中public function getMyDataAction(){    $data = [];    // your filters and all the logic to populate $data    $this->_helper->json($data);}请记住,ZF1 有几个性能问题,主要与资源配置有关,应尽可能用 serviceManager 替换,也可以用 Zend_Date 替换。
打开App,查看更多内容
随时随地看视频慕课网APP