Commit 92205143 authored by thibaut-felten's avatar thibaut-felten

Autoloader

parent 15d6be95
<?php
class AutoLoader {
public function __construct() {
......@@ -7,12 +9,37 @@ public function __construct() {
// This method will be automatically executed by PHP whenever it encounters an unknown class name in the source code
private function load($className) {
$classFile = "";
// TODO : compute path of the file to load (cf. PHP function is_readable)
// it is in one of these subdirectory '/classes/', '/model/', '/controller/'
// if it is a model, load its sql queries file too in sql/ directory
if(strpos($className, "Controller") !==FALSE){
$classFile .= "../controller/";
}else if(strpos($className, "Model") !==FALSE){
$classFile .= "../model/";
}else if(strpos($className, "Role") !==FALSE){
$classFile .= "../model/";
}else if(strpos($className, "User") !==FALSE){
$classFile .= "../model/";
}else if(strpos($className, "Response") !==FALSE){
$classFile .= "../classes/";
}else if(strpos($className, "Request") !==FALSE){
$classFile .= "../classes/";
}else if(strpos($className, "Dispatcher") !==FALSE){
$classFile .= "../classes/";
}else if(strpos($className, "DatabasePDO") !==FALSE){
$classFile .= "../classes/";
}
$classFile.=.$className.".class.php";
include $classFile;
}
}
$__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() {
// $db = new PDO("sqlite::memory");
$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) {
// TODO
}
}
\ 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 errorResponse($message = "") {
return new Response(400,$message);
}
public static function serverErrorResponse($message = "")
{
return new Response(500,$message);
}
public static function okResponse($message = "")
{
return new Response(200,$message);
}
public static function notFoundResponse($message = "")
{
return new Response(404,$message);
}
public static function errorInParametersResponse($message = "")
{
return new Response(400,$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',3306);
define('DB_DBNAME','dbtest');
define('DB_USER','root');
define('DB_PASSWORD','root');
\ 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 UsersController extends Controller {
public function __construct($name, $request) {
parent::__construct($name, $request);
}
// ==============
// Actions
// ==============
public function processRequest()
{
switch ($this->request->getHttpMethod()) {
case 'GET':
return $this->getAllUsers();
break;
}
return Response::errorResponse("unsupported parameters or method in users");
}
protected function getAllUsers()
{
$users = User::getList();
// TODO
return $response;
}
}
\ 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';
// load all users from Db
public static function getList() {
$stm = parent::exec('USER_LIST');
return $stm->fetchAll();
}
}
\ No newline at end of file
<?php
User::addSqlQuery('USER_LIST',
'SELECT * FROM USER ORDER BY USER_LOGIN');
User::addSqlQuery('USER_GET_WITH_LOGIN',
'SELECT * FROM USER WHERE USER_LOGIN=:login');
User::addSqlQuery('USER_CREATE',
'INSERT INTO USER (USER_ID, USER_LOGIN, USER_EMAIL, USER_ROLE, USER_PWD, USER_NAME, USER_SURNAME) VALUES (NULL, :login, :email, :role, :pwd, :name, :surname)');
User::addSqlQuery('USER_CONNECT',
'SELECT * FROM USER WHERE USER_LOGIN=:login and USER_PWD=:password');
\ 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