phpurlrestful-urltonic

Tonic.PHP on having "/resource" and "/resource/id" URL's


I'm trying to get the URL "/videoGame" to run "listAllVideoGames" method and "/videoGame/#" (Where # is a number) to run "getVideoGame" method. Changing priorities with "@priority" annotation I can make both URL's call one or the other but can't find the way to do what I described.

/**
 * @uri /videoGame
 * @uri /videoGame/:id
 */
class VideoGame extends Resource{

    protected function getDao(){
        return new VideoGameDao();
    }

    /**
     * @uri /videoGame
     * @json
     * @provides application/json
     * @method GET
     */
    public function listAllVideoGames(){
        return new Response(Response::OK,$this->dao->getAllVideoGames());
    }

    /**
     * @uri /videoGame/:id
     * @json
     * @provides application/json
     * @method GET
     */
    public function getVideoGame($id){
        $vg = $this->dao->getVideoGame($id);
        if ($vg){
            return new Response(Response::OK,$vg);
        }else{
            throw new NotFoundException();
        }
    }
}

Solution

  • The only way I found to do this is to create a kind of dispatcher for the GET calls like this:

    /**
     * @uri /videoGame
     * @uri /videoGame/:id
     */
    class VideoGame extends Resource{
    
        protected function getDao(){
            return new VideoGameDao();
        }
    
        /**
         * @uri /videoGame/:id
         * @provides application/json
         * @method GET
         */
        public function getVideoGames($id = 0){
            if (is_numeric($id) && $id > 0){
                return $this->getVideoGame($id);
            }else{
                return $this->getAllVideoGames();
            }
        }
    
        private function getVideoGame($id){
            $vg = $this->dao->getVideoGame($id);
            if ($vg){
                return new Response(Response::OK,$vg);
            }else{
                throw new NotFoundException();
            }
        }
    
        public function getAllVideoGames(){
            return new Response(Response::OK,$this->dao->getAllVideoGames());
        }