Created
November 2, 2012 17:30
-
-
Save alanpich/4002955 to your computer and use it in GitHub Desktop.
filesystem controller w/ Slim
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
header('Content-Type: text/plain'); | |
define('ROOT',dirname(dirname(__FILE__)).'/'); | |
define('CONTROLLER_PATH',ROOT.'controllers/'); | |
/** | |
* Initialize some Slim action | |
*/ | |
require ROOT.'lib/Slim/Slim/Slim.php'; | |
\Slim\Slim::registerAutoloader(); | |
$slim = new \Slim\Slim(); | |
/** | |
* Set Slim presets | |
*/ | |
\Slim\Route::setDefaultConditions(array( | |
'id' => '[0-9]' | |
)); | |
/** | |
* Parse /controllers directory | |
* All subfolders are names of url paths / controllers to map | |
*/ | |
$controllers = array(); | |
$nodes = scandir(CONTROLLER_PATH); | |
foreach($nodes as $node){ | |
if( is_dir(CONTROLLER_PATH.$node) && $node!='.' && $node != '..'){ | |
$controllers[] = $node; | |
} | |
} | |
/** | |
* Set up Slim listeners for each controller | |
*/ | |
foreach($controllers as $C){ | |
// Map GET | |
$slim->get("/$C(/:id(/:relation))",function($id = NULL,$relation = NULL){ | |
// Class Loader -> poss move to autoloader?? | |
$className = ucfirst($C).'Controller'; | |
if(! class_exists($className)){ | |
$controllerPath = CONTROLLER_PATH.$C.'/'.ucfirst($C).'.class.php'; | |
if(!file_exists($controllerPath)){ | |
die('horribly'); | |
} else { | |
include $controllerPath; | |
} | |
}; | |
// Instantiate controller | |
$controller = new $className; | |
// Select function based on path supplied | |
if($id==NULL && $relation==NULL){ | |
// Search all objects of this type | |
$controller->getMany($_GET); | |
} else { | |
if( $relation==NULL){ | |
// Return object by id | |
$controller->getOne($id); | |
} else { | |
// Return relations of this object | |
$controller->getRelation($id,$relation); | |
} | |
} | |
}); | |
}; | |
// Run Slim router | |
$slim->run(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment