phpzend-frameworkzend-framework2zend-framework3

A simple REST API implementation for a website created on ZF


I have a website that stores inventory and I need to make a REST API because I have to put the web component and deliver the data to it. Communication will be secured by JWT. I found a very simple solution zf3-rest-api but I can't implement it because I have some strange file structure (I don't have modules.config.php etc.) I'm afraid it's not ZF3 or even ZF2. I can write a custom solution but I don't know where should I put the code (sorry I am a front-end developer)? in modules? and how to deal with routing? so that I can refer to it via http://example.com/api/?

enter image description here


Solution

  • This is a ZF1 application tree and ZF1 has its REST implementation.

    You can get here an example of controller that extends Zend_Rest_Controller. Let's say you call it "MyRestfulController".

    then you must register your rest routes, you can do it in your 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);
    }
    

    OR

    If you do not need rest but just an API that return some JSON you may skip the Restful part and disable layout in you controller ( so not extending Zend_Rest_Controller ), overriding the "init()" method

        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;
    }
    

    Then in your action

    public function getMyDataAction()
    {
        $data = [];
    
        // your filters and all the logic to populate $data
    
        $this->_helper->json($data);
    }
    

    Keep in mind that ZF1 has several performances issues, mainly related to the resource configuration that should be replaced by serviceManager as much as possible, and also by Zend_Date.