This is a basic example for an api based on ReactPHP library.
It will show how to work with endpoints, and for this example we will use Games as a main item.
After cloning / downloading this repository please follow the next steps:
- npm install - download and install all required npm packages
- composer install - download and install all packages of PHP
We will use a nodemon to run our servers with reloading on file change.
To start nodemon process just type npm run dev
, it will start the server.php
After installing and downloading all the required packages from NPM and Composer you can use the rpc CLI tool to work
with this project.
First, please run (in root project folder).
npm link
After running the npm link
you can type
On windows
rpc --help
Or on Mac
./rpc.js --help
When running the command you should see the help section of the CLI.
If you have any problem running the CLI please contact me
All the data you will see in this REST API data, is managed via Helpers classes.
The helpers can be found in the src folder under Helpers directory.
The only reason the helpers are here, is to include an example data without the need to integrate DB.
When you finish to develop your API please delete Helpers directory and files and use your real data.
For this example we will use:
- /games - GET
- /games - GET (with game id)
- /games - POST (with game id)
- /games - DELETE (with game id)
- /games - PUT (with game id)
- /games - OPTIONS
- /userbalance - GET (with user id)
- /userbalance - PUT (with user id)
- /userbalance - OPTIONS
You can build a controller however you want.
I decided to go on with the ReactPHP convention and to make an __invoke method.
For every endpoint, can have multiple controllers files, when every file will be take care for single method.
What it means is, that if I have endpoint with a get and post methods, I will have 2 controllers for this single
endpoint.
If you do not want to use postman or other tool to check and test this API and you are using PHP Storm,
You can use the requests.http and run any request you want to check.
Above of every request you will find a comment with a basic explanation of the request.
The router class will valid that the request is valid and if an endpoint is not found it will return the error
response.
If the route is found and method is allowed it will dispatch the relevant endpoint
This file should hold all environment configurations and need to be ignored from git.
Yes, i know that all the platforms using .env file and its cool and fun but i have work to do here and don't have time
to find solutions.
To use env.ini data you can user the next function of php
parse_ini_file($_SERVER['DOCUMENT_ROOT'] . 'env.ini');
This will pass all the data from env.ini file parsed to array.
Good luck.