This article will share with you the methods and simple examples of using the RESTful interface written in PHP. if you need it, you can refer to it. First, let's get to know about RESTful.
Restful is a design style rather than a standard, for example an interface is originally like this: http://www.test.com/user/view/id/1
Obtains the user information with id 1. if the Restful style is used, it can be changed to the following:
Http://www.test.com/user/1
We can clearly see the benefits of doing so:
1. more concise URL, friendly to programmers
2. do not expose the internal code structure, making it safer
So how to implement this interface? First, we need to receive/user/1.
$path = $_SERVER['PATH_INFO']; $arr = explode('/',$path); print_r($arr);
The following result is displayed:
Array ( [0] => [1] => User [2] => 1 )
After obtaining the parameters, the following operations are simple:
If ($ arr [1] = 'user') {$ model = new UserModel (); $ id = $ arr [2]; // read User information $ user_info = $ model-> find ($ id); echo json_encode ($ user_info );}
In this way, we implement a Restful API.
Next, let's look at how to implement the interface to read the user list, the traditional way: http://www.test.com/user/list
The Restful style can be more concise:
Http://www.test.com/user
The difference with reading user information is that there is no id behind the user, so we can modify it based on the reading part:
If ($ arr [1] = 'user') {$ model = new UserModel (); $ id = $ arr [2]; if ($ id) {// read User information $ user_info = $ model-> find ($ id); echo json_encode ($ user_info );} else {// read the user list $ user_list = $ model-> select (); echo json_encode ($ user_list );}}
In this way, the interface for reading the user list is implemented.
The following describes how to add user interfaces. the traditional method is as follows:
Http://www.test.com/user/add
Restful style:
Http://www.test.com/user
It is the same as the interface for reading the user list. how can this problem be distinguished? In fact, it is very simple. reading is a GET request, but adding is a POST request. user information is included in the POST parameter, so you can modify the code as follows:
If ($ arr [1] = 'user') {$ model = new UserModel (); $ id = $ arr [2]; if ($ id) {// read User information $ user_info = $ model-> find ($ id); echo json_encode ($ user_info);} else {if (IS_POST) {// add user $ res = $ model-> add ($ _ POST); if ($ res) {echo 'success ';} else {echo 'fail ';}} else {// read the user list $ user_list = $ model-> select (); echo json_encode ($ user_list );}}}
For the same interface, different logic can be executed based on the HTTP request method.
This is the core idea of implementing Restful APIs, and so on. we can edit and delete user interfaces:
Http://www.test.com/user/1
As long as different request methods are used, they can be separated. We can use the PUT request to perform the edit operation, and the DELETE request to perform the DELETE operation.
The specific code will not be written. if you are interested, you can try to implement the following.
The Thinkphp framework also provides support for the Restful style, and the principle is similar.
To sum up, the Restful style is to use simple URLs and HTTP request methods to implement interfaces.
PHPRSGithub
This is a lightweight framework designed for rapid development of RESTful interfaces. If you are just like me, get tired of using the traditional MVC framework to write microservices or APIs separated from the frontend and backend, can't stand the lots of extra coding (and CTRL-C/CTRL-V) done for a simple interface, then you'll definitely love this frame!
Let's start with a chestnut.
Write HelloWorld. php and put it in the directory specified by the framework (the default is the apis/directory at the same level as index. php)
/** * @path("/hw") */class HelloWorld{ /** * @route({"GET","/"}) */ public function doSomething() { return "Hello World!"; }}
Enter http: // your-domain/hw/in the browser/
You will see: Hello World! It is so simple that no additional configuration is required, no inheritance or combination is required.
What happened
Looking back at HelloWorld. php, the special thing is that the annotation (@ path, @ route). That's right. The framework obtains the route information and binds the input and output through the annotation. But don't worry about performance. the comment will only be parsed once after the class file is modified. More @ comments will be described later.
Let's look at a more specific example.
This is an example of a logon interface.
/*** User permission verification * @ path ("/tokens /") */class Tokens {/*** logon * authorization by username and password * @ route ({"POST", "/accounts/"}) * @ param ({"account ", "$. _ POST. account "}) account * @ param ({" password "," $. _ POST. password "}) password ** @ throws ({" InvalidPassword "," res "," 403 Forbidden ", {" error ":" InvalidPassword "}}) invalid username or password ** @ return ({"body"}) * returns the token, which is the same as the token in the cookie. * {"token": "xxx ", "uid" = "xxx"} ** @ return ({"cookie", "token", "$ token", "+ 365 days ","/"}) return token * @ return ({"cookie", "uid", "$ uid", "+ 365 days", "/"}) through cookie ","/"}) return uid */public function createTokenByAccounts ($ account, $ password, & $ token, & $ uid) through cookie) {// Verify the user $ uid = $ this-> users-> verifyPassword ($ account, $ password); Verify: isTrue ($ uid, new InvalidPassword ($ account )); $ token = ...; return ['token' => $ token, 'uid' => $ uid];}/*** @ property ({"default": "@ Users "}) dependency attribute, injected by the framework * @ var Users */public $ users ;}
What else can I do?
- Dependency Management (dependency injection ),
- Automatic output interface document (not a doxgen-type class or method document, but a document describing the http interface)
- Interface cache
- Hook
Access the database with ezsql
Ezsql is a simple object-oriented SQL build tool that provides simple basic SQL operations.
Interface
/** @ Path (/myclass) */class MyClass {/*** @ route ({"GET", "/do "}) * @ param ({"arg0", "$. _ GET. arg0 "}) */public doSomething ($ arg0) {return SQL: select ('XXX')-> from ('Table _ XXX ') -> where ('XXX =? ', $ Arg0)-> get ($ this-> db);}/*** dependency injection PDO instance * @ property * @ var PDO */public $ db ;}
Configuration file
{ { "MyClass":{ "properties":{ "db":"@db1" } }, }, "db1":{ "singleton":true, "class":"PDO", "pass_by_construct":true, "properties":{ "dsn":"mysql:host=127.0.0.1;dbname=xxx", "username":"xxxx", "passwd":"xxxx" } },}