PHP Classes
elePHPant
Icontem

PHP REST Framework: Handle REST requests with command classes

Recommend this page to a friend!
  Info   View files View files (30)   DownloadInstall with Composer Download .zip   Reputation   Support forum   Blog    
Last Updated Ratings Unique User Downloads Download Rankings
2014-02-10 (2 years ago) RSS 2.0 feedNot enough user ratingsTotal: 754 This week: 2All time: 4,265 This week: 591Up
Version License PHP version Categories
php-rest 1.0GNU General Publi...5.4PHP 5, Libraries, Web services
Description Author

This package is a framework to handle REST requests with command classes.

It can process and route HTTP requests to command classes based on the REST request URL.

The command class objects are instantiated by the observer class which may call the command objects to execute the request REST API action.

If necessary an API request token is checked to authorize the action API call access.

The command classes are responsible for returning the request response data.

Picture of Pashkov Denis Igorevich
  Performance   Level  
Name: Pashkov Denis Igorevich <contact>
Classes: 21 packages by
Country: Ukraine Ukraine
Innovation award
Innovation award
Nominee: 10x

Winner: 1x

Details
PDF VERSION :    https://github.com/andromeda1913/php-rest-api-framework/




1 Overview
2 Structure
3 Method Overview 4 Quick Start

PHP Simple REST Framework :


This document describes structure and functionality of the Framework Classes. This framework can be used to create "JSON Api web service»
Structure of the REST requests : http://server.com/api/users/getlist?fget=1 -
1 http://server.com - domain of the service
2 /api/ - subDirectory where framework files are located 3 /users/ - Name of the Class .
4 /getlist - get method name in the class
5 fget - some get variables


Structure of the Framework :
-- Root -- api
--commands --Helpers --media --models --tmp
--Bootstrap.php --config.php --index.php --Observer.php --REquest.php --Response.php --serviceDesc.txt
--.htaccess



1 Commands - This Directory contains all Classes required for your service .
Each classes should be named exactly as the name of the method for
example Users.php
returns Response object.
Will be accessible with the followed request



http:// server.com/api/Users/name_of_the_method inside Users class that
Each Class should be extended From Abstract method Class.
2 Helpers - This folder contains static Helpers classes that you can use in your commands or models
3 media - contains all media uploaded file
4 tmp - contains temporary files
5 models - Contains all models Classes extended from base Abstract Model .
. Methods Overview:
Commands Abstract Methods :
requireToken() ; - This method need to be called inside methods that requires secure token $_GET[“token”] ; see Quick start section :
allowCache(); -- this method should be called inside methods that allowing cache output result in memcache ;
disableCache(); -- disable cache for current method ;
setError($msg) ; -- Creates Error Json response with error string ;


Execute(\Request $req = null) ; -- Default method will be executed on each Commands Class ; hasResponse() ; -- returns true or false if current Command has Reponse.





Model Abstract Methods:



public function setTable($table) Set Name of the Table For model ; public function delete($id) -- Remove record By id in current table ; public function setSql($sql) -- Set Raw SQl;
public function exec() -- Execute Raw SQL ;
public function selectAll()-- Select all from raw SQL request ;
public function load() -- Load Single Object Record from sql raw request ; public function loadList() -- Load list of object from raw Request ;
public function selectByAll($field, $v) -- Select record set Where field = v ;
public function generalInsert($data = []) -- insert Key – value into the table .
public function updateBypost($post = []) -- Update record “If dataset contains id key ”
public function createToken($data_users = [] ) -- Create Secure Token with Custom Data ;
returns hash string
public function getFromToken($name , $var) -- Get data from token by hash and var name ;

Request Method
public function contains($name) -- return true or false if request cdontains variable
public function get($name) -- get request get or post variable ;

Response Object methods
public function __construct($status = true, $error = false , $error_m = "") – default constructor ; public function add($key , $val=null ) -- add key value into data response array ;

Observer Methods:
public function UploadFile($path = '', $prefix = '' ) -- upload single File and returns the name of the file
$path – default upload path FROM BASE_DIR ;
$prefix prefix name of the file ;
public function UploadFiles($path = '', $prefix = '' ) -- Upload Multiply Files and return array of file names ; public function createThumbnail($filename, $prefix = '_small' ) – Create image Thumbnail
public function sendFile($filename = 'file.csv', $data = '') -- Send file to the end user with headers ; public function auto_link($str) -- Auto link string ;
public function saveHTML($str) – strip some html tags ;
public function compress ($buffer) -- compress string;

Quick Start :
1 Grab your copy From GitHub . it requires php 5.4 or later ; 2 Place it on your web server for example in /api/directory ;
3 Edit .htaccess Change RewriteBase 4 Open And Edit config.php
Edit Database Settings :
HOST mysql server
USER mysql username
PASS mysql password DATABASE name of database
DEVELOP - true - false ; display or not errors
START_PATH - Integer value for Parsing url if your service is in subdirectory the start path will be start from 3 else if root directory you should change it to 2
SITE_NAME - Name of the service will be display in each response
VERSION - string will be output in Json Response
FORMAT - “JSON” / “XML” Format of the output ;
SMTP_HOST SMTP_USER SMTP_PASS NOTIFY_EMAIL - SMTP settings For Mail Helper
5 Test it / open url in your browser http://your.com/api will be output default response with Timestamp

CREATE SIMPLE “HELLO WORLD”
When after that we finished configuration, let’s create simple hello World Service. Lets start with creating a simple table in our database.
Create Table “Users” with fields : id, username , email ;
In models directory create file Users.php in that file create Class Users extended from _Abstract
You should get something like :
<?php
namespace models;
class Users extends _Abstract{
}
and create constructor :
public function __construct(){
parent::__construct() ;
$this->setTable("Users") ; // set Table For that
model ;
}
Ok we have created model For Users model, time Create our Actions
Lets create action that will have methods for register new user, login, and get users list;
In /Api/commands / create class Users file name Users.php
<?php
namespace commands;
class Users extends _Abstract{
public function hasResponse(){ return true ;
}
}
// ok let’s create Business logic ;
in our model Users add method That will insert new user
public function insertUser($username , $email){ $id = $this->generalInsert([
"username"=>$username,
"email"=>$email , ]);
return $id ; }
in commands/Users create method that will encapsulate login register :
public function register(\Request $req = null ){ if ($req->contains("username")&&$req-
>contains("email")){
$model = new Users() ;
// Create user and add id in response
$this->responseObject->add("user_id", $model->insertUser( $req->get("username") ,
$req->get("email")));
} else{
$this->setError("username ,email required") ;
}
return $this->responseObject ;
}
// Great now we can create new users in our table :
like this http://server.com/api/users/register?username=some&email=some
now it’s time to create login method in Command/users create method login
public function login(\Request $req = null){ $model = new Users() ;
$username = $req->get("username") ;
if ($username){
// try to find out user
$id = $model->login($username); if ($id) {
$this->responseObject->add("user_id", $id) ; $this->responseObject->add("token", $model-
>createToken()) ;
}else{
$this->setError("User Not Found") ;
}
}else{
$this->setError("Please enter username") ;
}
return $this->responseObject ; }

ok for login we just need to call
http://server.com/users/login?username=some
note this is the test , so there is no password etc. anyway , on success it will return :
user_id , token ;
token we will gonna need that in our last method called “get users List” :
Lets Create method in our controller that will return list of users for logged users ;
public function getlist(\Request $req = null){ $model = new Users();
$this->requireToken() ; // Token Required For that method ; $all = $model->selectAll(); $this->responseObject->add("all", $all) ;
return $this->responseObject; }
This method should be called : http://server.com/api/users/getlist?token=...... . token string
See full example in repository:
  Files folder image Files  
File Role Description
Files folder imageapi (9 files, 4 directories)
Plain text file Readme.txt Doc. Readme
Plain text file usingXMLresponse.txt Doc. XML

  Files folder image Files  /  api  
File Role Description
Files folder imagecommands (5 files)
Files folder imageHelpers (6 files)
Files folder imagemodels (2 files)
Files folder imagetmp (6 files)
  Plain text file .htaccess Data htaccess
  Plain text file Bootstrap.php Class Bootstrap
  Plain text file config.php Conf. Main config
  Plain text file index.php Example index
  Plain text file Observer.php Class Observer
  Plain text file Request.php Class REquest
  Plain text file Response.php Class REsponse
  Plain text file ResponseXML.php Class res
  Plain text file serviceDesc.txt Data desc

  Files folder image Files  /  api  /  commands  
File Role Description
  Plain text file Token.php Class class file
  Plain text file Tokentest.php Class class file
  Plain text file Users.php Class class file
  Plain text file Version.php Class class file
  Plain text file _Abstract.php Class class file

  Files folder image Files  /  api  /  Helpers  
File Role Description
  Plain text file Cached.php Class class file
  Plain text file class.phpmailer.php Class class file
  Plain text file class.pop3.php Class class file
  Plain text file class.smtp.php Class class file
  Plain text file Email.php Class class file
  Plain text file _Abstract.php Class class file

  Files folder image Files  /  api  /  models  
File Role Description
  Plain text file Users.php Class class file
  Plain text file _Abstract.php Class class file

  Files folder image Files  /  api  /  tmp  
File Role Description
  Plain text file 0a73d62edc64bcc3fa63076a68eaed4f Data class file
  Plain text file 732620f514b35c4564736321e6219677 Data class file
  Plain text file 80483e7e433c9f5b9b567537695a40af Data class file
  Plain text file b9d88432de930c54969811497341e42e Data class file
  Plain text file e27f5747615ff0f669528d460ed7228a Data class file
  Plain text file ec2902b55eebe89217fca9ef9c7d5992 Data class file

 Version Control Unique User Downloads Download Rankings  
 96%
Total:754
This week:2
All time:4,265
This week:591Up