Commit 0c0987b1 authored by Raphaël Peim's avatar Raphaël Peim

Reorganize repository

parent 9d916fbe
......@@ -10,14 +10,13 @@
}
protected static function createPDO() {
// $db = new PDO("sqlite::memory");
$connectionString = "mysql:host=". DB_HOST;
if(defined('_MYSQL_PORT'))
if(defined('DB_PORT'))
$connectionString .= ";port=". DB_PORT;
$connectionString .= ";dbname=" . DB_DATABASE;
$connectionString .= ";charset=utf8";
static::$pdo = new PDO($connectionString, DB_USERNAME, DB_PASSWORD);
static::$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
......
......@@ -37,8 +37,8 @@
// $uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_QUERY);
$route = getRoute($uri);
$requestMethod = $_SERVER["REQUEST_METHOD"];
$controllerName = $route['controller'];
$requestMethod = $_SERVER["REQUEST_METHOD"];
switch($controllerName) {
case 'users' :
......
<?php
// define __ROOT_DIR constant which contains the absolute path on disk
// of the directory that contains this file (index.php)
// e.g. http://eden.imt-lille-douai.fr/~luc.fabresse/index.php => __ROOT_DIR = /home/luc.fabresse/public_html
$rootDirectoryPath = realpath(dirname(__FILE__));
define ('__ROOT_DIR', $rootDirectoryPath );
// Load all application config
require_once(__ROOT_DIR . "/config/config.php");
// Load the Loader class to automatically load classes when needed
require_once(__ROOT_DIR . '/classes/AutoLoader.class.php');
// Reify the current request
$request = Request::getCurrentRequest();
Response::interceptEchos();
try {
$controller = Dispatcher::dispatch($request);
$response = $controller->execute();
} catch (Exception $e) {
$log = Response::getEchos();
$log .= " " . $e->getMessage();
$response = Response::errorResponse($log);
}
$response->send();
?>
\ No newline at end of file
<?php
class AutoLoader {
public function __construct() {
spl_autoload_register( array($this, 'load') );
// spl_autoload_register(array($this, 'loadComplete'));
}
// This method will be automatically executed by PHP whenever it encounters an unknown class name in the source code
private function load($className) {
$paths = array('/classes/', '/controller/', '/model/', '/sql/');
$fileToLoad = null;
$i = 0;
do {
$fileToLoad = __ROOT_DIR . $paths[$i] . ucfirst($className) . '.class.php';
$i++;
} while(!is_readable($fileToLoad) && $i < count($paths));
if (!is_readable($fileToLoad))
throw new Exception('Unknown class ' . $className);
require_once($fileToLoad);
if (strlen(strstr($fileToLoad, '/model/')) > 0) {
$fileToLoadSql = __ROOT_DIR . '/sql/' . ucfirst($className) . '.sql.php';
if (is_readable($fileToLoadSql)) {
require_once($fileToLoadSql);
}
}
}
}
$__LOADER = new AutoLoader();
?>
\ No newline at end of file
<?php
class DatabasePDO extends PDO {
protected static $singleton = NULL;
public static function singleton(){
if(is_null(static::$singleton))
static::$singleton = new static();
return static::$singleton;
}
public function __construct() {
$connectionString = "mysql:host=". DB_HOST;
if(defined('DB_PORT'))
$connectionString .= ";port=". DB_PORT;
$connectionString .= ";dbname=" . DB_DATABASE;
$connectionString .= ";charset=utf8";
parent::__construct($connectionString, DB_USERNAME, DB_PASSWORD);
$this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
}
?>
\ No newline at end of file
<?php
/*
* Analyses a request, created the right Controller passing it the request
*/
class Dispatcher {
public static function dispatch($request) {
return static::dispatchToController($request->getControllerName(), $request);
}
public static function dispatchToController($controllerName, $request) {
$controllerClassName = ucfirst($controllerName) . 'Controller';
if (!class_exists($controllerName))
throw new Exception("$controllerName does not exist");
return new $controllerClassName($controllerName, $request);
}
}
?>
\ No newline at end of file
<?php
class Request {
protected $controllerName;
protected $uriParameters;
protected static $singleton = NULL;
public function __construct() {
$this->jsonReceived = null;
$this->initBaseURI();
$this->initControllerAndParametersFromURI();
}
public static function getCurrentRequest() {
if (is_null(static::$singleton))
static::$singleton = new static();
return static::$singleton;
}
// intialise baseURI
// e.g. http://eden.imt-lille-douai.fr/~luc.fabresse/api.php => __BASE_URI = /~luc.fabresse
// e.g. http://localhost/CDAW/api.php => __BASE_URI = /CDAW
protected function initBaseURI() {
$this->baseURI = explode('/api.php', $_SERVER['SCRIPT_NAME'])[0];
}
// intialise controllerName et uriParameters
// controllerName contient chaîne 'default' ou le nom du controleur s'il est présent dans l'URI (la requête)
// uriParameters contient un tableau vide ou un tableau contenant les paramètres passés dans l'URI (la requête)
protected function initControllerAndParametersFromURI(){
$url = trim($_SERVER['PATH_INFO'], '/');
$urlSegments = explode('/', $url);
$scheme = ['controller', 'params'];
$route = [];
foreach ($urlSegments as $index => $segment){
if ($scheme[$index] == 'params'){
$route['params'] = array_slice($urlSegments, $index);
break;
} else {
$route[$scheme[$index]] = $segment;
}
}
$this->controllerName = $route['controller'] != "" ? $route['controller'] : "default";
$this->uriParameters = isset($route['params']) ? $route['params'] : [];
}
// ==============
// Public API
// ==============
// retourne le name du controleur qui doit traiter la requête courante
public function getControllerName() {
return $this->controllerName;
}
// retourne la méthode HTTP utilisée dans la requête courante
public function getHttpMethod() {
return $_SERVER["REQUEST_METHOD"];
}
public function getUriParameters() {
return $this->uriParameters;
}
}
?>
\ No newline at end of file
<?php
class Response {
protected $code;
protected $body;
public function __construct($code = 404, $msg = "") {
$this->code = $code;
$this->body = $msg;
}
public static function okResponse($message = "")
{
return new Response(200, $message);
}
public static function errorResponse($message = "") {
return new Response(400, $message);
}
public static function errorInParametersResponse($message = "")
{
return new Response(400, $message);
}
public static function notFoundResponse($message = "")
{
return new Response(404, $message);
}
public static function serverErrorResponse($message = "")
{
return new Response(500, $message);
}
public static function interceptEchos() {
ob_start();
}
public static function getEchos() {
return ob_get_clean();
}
public function send() {
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Methods
header("Access-Control-Allow-Methods: GET,POST,PUT,DELETE");
header("Access-Control-Max-Age: 3600"); // Maximum number of seconds the results can be cached.
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Headers
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
http_response_code($this->code);
echo $this->body;
exit; // do we keep that?
}
}
?>
\ No newline at end of file
<?php
define('DB_HOST', 'localhost');
define('DB_PORT', 8888);
define('DB_DATABASE', 'dbtest');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', 'root');
// define('__DEBUG', false);
define('__DEBUG', true);
// ================================================================================
// Debug utilities
// ================================================================================
if(__DEBUG) {
error_reporting(E_ALL);
ini_set("display_errors", E_ALL);
} else {
error_reporting(0);
ini_set("display_errors", 0);
}
function myLog($msg) {
if(__DEBUG) {
echo $msg;
}
}
function myDump($var) {
if(__DEBUG) {
var_dump($var);
}
}
?>
\ No newline at end of file
<?php
/*
* A Controller is dedicated to process a request
* its responsabilities are:
* - analyses the action to be done
* - analyses the parameters
* - act on the model objects to perform the action
* - process the data
* - call the view and passes it the data
* - return the response
*/
abstract class Controller {
protected $name;
protected $request;
public function __construct($name, $request) {
$this->request = $request;
$this->name = $name;
}
public abstract function processRequest();
public function execute() {
$response = $this->processRequest();
if(empty($response)) {
// $response = Response::serverErrorResponse("error processing request in ". self::class); // Oh my PHP!
$response = Response::serverErrorResponse("error processing request in ". static::class);
}
return $response;
}
}
?>
\ No newline at end of file
<?php
class DefaultController extends Controller {
public function __construct($name, $request) {
parent::__construct($name, $request);
}
// ==============
// Actions
// ==============
public function processRequest() {
return Response::errorResponse('{ "message" : "Unsupported endpoint"}' );
}
}
?>
\ No newline at end of file
<?php
class UserController extends Controller {
public function __construct($name, $request) {
parent::__construct($name, $request);
}
// ==============
// Actions
// ==============
public function processRequest() {
switch ($this->request->getHttpMethod()) {
case 'POST':
return $this->createUser($_POST);
break;
case 'GET':
if (empty($this->request->getUriParameters()))
return $this->getAllUsers();
else
return $this->getUserById($this->request->getUriParameters()[0]);
break;
case 'PUT':
$put = json_decode(file_get_contents("php://input"));
$id = $this->request->getUriParameters()[0];
return $this->updateUser($put, $id);
break;
case 'DELETE':
$id = $this->request->getUriParameters()[0];
return $this->deleteUser($id);
break;
}
return Response::errorResponse("unsupported parameters or method in users");
}
protected function createUser($post) {
if (isset($post['name']) && isset($post['email'])) {
User::create($post);
$response = Response::okResponse("Utilisateur ajouté");
}
else {
$response = Response::notFoundResponse("Aucun utilisateur ajouté");
}
return $response;
}
protected function getAllUsers() {
$users = User::getList();
if (!empty($users))
$response = Response::okResponse(json_encode($users));
else
$response = Response::notFoundResponse("Aucune réponse");
return $response;
}
protected function getUserById($id) {
$user = User::getWithId($id);
if (!empty($user))
$response = Response::okResponse(json_encode($user));
else
$response = Response::notFoundResponse("Aucune réponse");
return $response;
}
protected function updateUser($put, $id) {
$user = User::getWithId($id);
if (!empty($put) && !empty($user)) {
User::update($put, $id);
$response = Response::okResponse("Utilisateur modifié");
}
else {
$response = Response::notFoundResponse("Aucun utilisateur modifié");
}
return $response;
}
protected function deleteUser($id) {
$user = User::getWithId($id);
if (!empty($user)) {
User::delete($id);
$response = Response::okResponse("Utilisateur supprimé");
}
else {
$response = Response::notFoundResponse("Aucun utilisateur supprimé");
}
return $response;
}
}
?>
\ No newline at end of file
<?php
phpinfo();
?>
\ No newline at end of file
<?php
class Model {
protected static function db(){
return DatabasePDO::singleton();
}
// *** Queries in sql/model.sql.php ****
protected static $requests = array();
public static function addSqlQuery($key, $sql){
static::$requests[$key] = $sql;
}
public static function sqlQueryNamed($key){
return static::$requests[$key];
}
protected static function query($sql){
$st = static::db()->query($sql) or die("sql query error ! request : " . $sql);
$st->setFetchMode(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE, get_called_class());
return $st;
}
protected static function exec($sqlKey, $values=array()){
$sth = static::db()->prepare(static::sqlQueryNamed($sqlKey));
$sth->setFetchMode(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE, get_called_class());
$sth->execute($values);
return $sth;
}
}
?>
\ No newline at end of file
<?php
class User extends Model {
// ===========
// = Statics =
// ===========
protected static $table_name = 'USER';
public static function create($post) {
parent::exec('USER_CREATE', [':name' => $post['name'], ':email' => $post['email']]);
}
public static function getList() {
$stm = parent::exec('USER_GET_LIST');
return $stm->fetchAll();
}
public static function getWithId($id) {
$stm = parent::exec('USER_GET_WITH_ID', [':id' => $id]);
return $stm->fetchAll();
}
public static function update($put, $id) {
parent::exec('USER_UPDATE', [':name' => $put->name, ':email' => $put->email, ':id' => $id]);
}
public static function delete($id) {
parent::exec('USER_DELETE', [':id' => $id]);
}
}
?>
\ No newline at end of file
<?php
User::addSqlQuery('USER_CREATE',
'INSERT INTO `users` VALUES (NULL, :name, :email)');
User::addSqlQuery('USER_GET_LIST',
'SELECT * FROM `users` ORDER BY `id` ');
User::addSqlQuery('USER_GET_WITH_ID',
'SELECT * FROM `users` WHERE `id` = :id');
User::addSqlQuery('USER_UPDATE',
'UPDATE `users` SET `name` = :name, `email` = :email WHERE `id` = :id');
User::addSqlQuery('USER_DELETE',
'DELETE FROM `users` WHERE `id` = :id');
?>
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment