Skip to content

Instantly share code, notes, and snippets.

@Piterden
Forked from splittingred/.htaccess
Created April 26, 2016 20:36
Show Gist options
  • Save Piterden/2115b5f93d7d18c384f999dce619d8a7 to your computer and use it in GitHub Desktop.
Save Piterden/2115b5f93d7d18c384f999dce619d8a7 to your computer and use it in GitHub Desktop.
Example of how to use new REST server class in MODX 2.3+
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-s
RewriteRule ^(.*)$ rest/index.php?_rest=$1 [QSA,NC,L]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^(.*)$ rest/index.php [QSA,NC,L]
</IfModule>
<?php
/**
* Found at: Controllers/Box.php
*
* Handle requests to [URL]/Controllers/Box. Automagically handles CRUD (GET/POST/PUT/DELETE) for the xPDOObject class myBox.
*/
class myControllersBox extends modRestController {
public $classKey = 'myBox';
public $defaultSortField = 'name';
public $defaultSortDirection = 'DESC';
}
<?php
/**
* Place in /rest/ directory of site. Add .htaccess file above. Note that our REST controllers are in /rest/Controllers/; they can be anywhere though - just change the basePath config option.
*/
/* first load MODX externally */
require_once '/path/to/modx/config.core.php';
require_once MODX_CORE_PATH . 'model/modx/modx.class.php';
$modx = modX::getInstance('rest');
$modx->addPackage('myboxes','/path/to/myboxes/model');
/* now load the REST service */
$rest = $modx->getService('rest','rest.modRestService','',array(
'basePath' => dirname(__FILE__).'/Controllers/',
'controllerClassSeparator' => '',
'controllerClassPrefix' => 'myControllers',
'xmlRootNode' => 'response',
));
$rest->prepare();
if (!$rest->checkPermissions()) {
$rest->sendUnauthorized(true);
}
$rest->process();
/**
* A GET request to our controller at /rest/box.js will output something like this:
*/
{
results: [{
id: 1,
name: 'A Blue Box',
width: 20,
height: 40
},{
/* etc */
}]
,total: 23
}
<!--
A GET request to our controller at /rest/box.xml, however, will output something like this - the class automatically handles XML/JSON output types:
-->
<response>
<results>
<result>
<id>1</id>
<name>A Blue Box</name>
<width>20</width>
<height>40</height>
</result>
<result>
<!-- etc -->
</result>
</results>
<total>23</total>
</response>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment