phprs
Lightweight, easy-to-use and jax-rs like RESTful framework.中文文档
Requirements
PHP5.4+
Features
- @Annotation
- IoC
- Auto document
- Cache
- Hook
- More...
Hello World
-
Put HelloWorld.php in your-project-dir/apis/
/** * @path("/hw") */ class HelloWorld { /** * @route({"GET","/"}) */ public function doSomething() { return ['msg'=>'Hello World!']; } }
-
{ "msg":"Hello World!" }
What happened
See HelloWorld.php, the annotations like @path,@route are used to define routers. Phprs also use annotations for two-way parameter binding, dependency injection, etc.
Examples
A login api example
/**
* authentication
* @path("/tokens/")
*/
class Tokens
{
/**
* login
* login with password
* @route({"POST","/accounts/"})
* @param({"account", "$._POST.account"}) user's account
* @param({"password", "$._POST.password"}) user's password
*
* @throws ({"InvalidPassword", "res", "403 Forbidden", {"error":"InvalidPassword"} }) invalid password or account
*
* @return({"body"})
* return uid
* {"uid" = "xxx"}
*
* @return({"cookie","token","$token","+365 days","/"}) return token with cookie
* @return({"cookie","uid","$uid","+365 days","/"}) return uid with cookie
*/
public function createTokenByAccounts($account, $password, &$token,&$uid){
$uid = $this->users->verifyPassword($account, $password);
Verify::isTrue($uid, new InvalidPassword($account));
$token = ...;
return ['uid'=>$uid];
}
/**
* @property({"default":"@Users"}) inject an instantiation of 'Users'
* that means $this->users will be initialized as 'Users' before __construct() called
*
* @var Users
*/
public $users;
}
Installation
-
Download and copy phprs-restful/lib/* --> your-project-dir/../lib/
-
new index.php --> your-project-dir/
<?php use caoym\util\IoCFactory; use caoym\util\ClassLoader; require_once __DIR__.'/../lib/caoym/AutoLoad.php'; ClassLoader::addInclude(__DIR__.'/apis/'); $factory = new IoCFactory(__DIR__.'/conf.json'); $router = $factory->create('caoym\\phprs\\RouterWithCache'); $router();
-
new conf.json --> your-project-dir/
{ }
-
Mkdir your-project-dir/apis/ and puy your owner api files
-
Settiing webserver, route RESTful requests to index.php, for example:
Nginx
location / { try_files $uri $uri/ /index.php?$args; }
Apache
RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteCond $1 !^(index\.php) RewriteRule ^(.*)$ /index.php/$1 [L]