Skip to content

Instantly share code, notes, and snippets.

@kojilab
Last active August 29, 2015 14:13
Show Gist options
  • Save kojilab/c2c7e4e67063ead5dc37 to your computer and use it in GitHub Desktop.
Save kojilab/c2c7e4e67063ead5dc37 to your computer and use it in GitHub Desktop.
Phalcon - Quick way to expose Mongo collection as a Rest API
<?php
use Phalcon\DI\FactoryDefault,
Phalcon\Mvc\Micro,
Phalcon\Config\Adapter\Ini as IniConfig,
Phalcon\Mvc\Micro\Collection as MicroCollection;
$di = new FactoryDefault();
$di->set('url', function(){
$url = new Phalcon\Mvc\Url();
$url->setBaseUri('/');
return $url;
});
$di->set('mongo', function() {
$mongo = new MongoClient();
return $mongo->selectDB("nugs");
}, true);
$di->set('collectionManager', function(){
return new Phalcon\Mvc\Collection\Manager();
}, true);
class RestMicro extends Phalcon\Mvc\Micro
{
public function __construct(Phalcon\DI\FactoryDefault $di, array $collectionNames = array())
{
$this->setDI($di);
foreach($collectionNames as $name)
{
$collection = new MicroCollection();
$controller = ucfirst($name).'ApiController';
if (!class_exists($controller))
{
$controller = 'RestApiController';
}
$controller = new $controller();
$controller::$collectionName = $name;
$collection->setHandler(new $controller());
$collection->setPrefix('/'.$name);
foreach($controller::$routes as $method => $routes)
{
foreach($routes as $path => $func)
{
$collection->$method($path, $func);
}
}
$this->mount($collection);
// load model classes
require_once(dirname(__FILE__).'/models/'.ucfirst($name).'.php');
}
}
}
class RestApiController extends Phalcon\Mvc\Controller
{
static public $routes = array(
'get' => array(
'/' => 'index',
'/{id}' => 'show'
),
'post' => array(
'/' => 'create'
),
'put' => array(
'/{id}' => 'update'
),
'delete' => array(
'/{id}' => 'delete'
),
);
static public $collectionName;
public function index()
{
if (!self::$collectionName)
{
$modelClass = str_replace('ApiController', '', get_class($this));
}
else
{
$modelClass = self::$collectionName;
}
$items = $modelClass::find();
foreach ($items as $item)
{
$data[] = $item->toArray();
}
echo json_encode($data);
}
public function show()
{
}
public function create()
{
}
public function update()
{
}
public function delete()
{
}
}
/*
just pass your collection names
you can also override the controller by creating ModelsApiController class if you want to customize methods
class UsersApiController extends RestApiController
{
public function index()
{
echo "hi";
}
}
*/
$app = new RestMicro($di, array('users'));
$app->handle();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment