CMS MADE SIMPLE FORGE

CMS Made Simple Core

 

[#10467] REST VERB support in actions

avatar
Created By: Robert Campbell (calguy1000)
Date Submitted: 2015-03-27 12:52

Assigned To: Robert Campbell (calguy1000)
Resolution: Fixed
State: Open
Summary:
REST VERB support in actions
Detailed Description:
It would be nice (yes, I am saying it this time) to have some sort of method
whereby for AJAX/restful type of requests
one could either register the route AND the verb.  Verb is something like PUT,
PATCH, DELETE, HEAD, GET, POST, ...

i.e: <verb> mysite.com/<object>/<id>

OR

Register the normal route and have a magic file in the module API called 
rest.<verb>.<action>.php that would respond to those requests appropriately and
error if there were no matching files (or no matching fallback action).

History

Comments
avatar
Date: 2016-04-07 11:33
Posted By: Robert Campbell (calguy1000)

for future reference.... any module can do this now with a single layer of
abstraction.

I have (in one module) an action called action.rest.php...  you can register a
route to this action if you want.

There is some code in this action that looks like this:

    $controller = \cge_param::get_string($params,'mymodule_controller');
    $class = "\\controllers\\$controller";
if( !class_exists($class) ) throw new
\ControllerNotFoundException("Controller $controller not found (looking for
class $class)");
    $req_method = strtolower(trim($_SERVER['REQUEST_METHOD']));

// here we're gonna merge in $_REQUEST with $params again just to handle GET
and POST data
    $params = array_merge($_REQUEST,$params);

    $obj = new $class($this);
    $obj->$req_method($params);

This gets the controller class name from a GET/POST parameter named
mymodule_controller, instantiates a new object of that class, gets the request
method... and then calls the appropriate method.   My base controller class
looks like:
abstract class controller
{
    protected $_mod;

    public function __construct(\ImOK $mod)
    {
        $this->_mod = $mod;
    }

    public function __call($method,$args)
    {
        throw new \BadMethodCallException('Method not supported');
    }
}

A derived controller class might look like:

class myController extends \controller
{
    function get($params)
    {
        // handle GET requests to this controller
    }

   function post($params)
   {
       // handle POST requests to this controller.
   }
}


      
avatar
Date: 2017-11-20 19:06
Posted By: Robert Campbell (calguy1000)

Controllers can now be classes in CMSMS 2.3
using the invoke method().

And then controller classes can route to different functions for different
request methods.
      
Updates

Updated: 2017-11-20 19:06
resolution_id: 5 => 7

Updated: 2016-04-07 11:33
resolution_id: => 5