r/PHPhelp • u/AngelSlash • Dec 11 '24
Solved Creating a REST API
Hello everyone
As the title says I'm trying to create a REST API. For context, I'm currently creating a website (a cooking website) to learn how to use PHP. The website will allow users to login / sign in, to create and read recipes. After creating the front (HTML, CSS) and the back (SQL queries) I'm now diving in the process of creating my API to allow users to access my website from mobile and PC. (For context I'm working on WAMP).
The thing is I'm having a really hard time understanding how to create an API. I understand it's basically just SQL queries you encode / decode in JSON (correct me if I'm wrong) but I don't understand how to set it up. From what I've gathered you're supposed to create your index.php and your endpoints before creating the HTML ? How do you "link" the various PHP pages (for exemple I've got a UserPage.php) with the endpoints ?
Sorry if my question is a bit confusing, the whole architecture of an API IS still confusing to me even after doing a lot of research about it. Thanks to anyone who could give me an explaination.
View all comments
Show parent comment
0
u/[deleted] Dec 12 '24
Well i can't roll up half a framework in a single comment. What you show is only the query builder path, not the ORM part. Also we are talking about vanilla implementations and not frameworks, so a proper response should be how to implement ORM on your own.
A basic ORM implementation would be to create a base Model class with the basic query functions : insert, select, update ..etc and extend your models from this class, so
abstract class Model{
protected $tableName = '';
public function insert(){
...SELECT * FROM $tableName WHERE .....
foreach self properties -> bind params to query
}
}
UserModel extends Model{
public int $id;
public string $firstName;
....
__construct(){
$tableName = 'users';
}
}
Now the UserModel class (and every other) does not need to contain an insert function at all, nor select, update, delete etc.. You just go:
$userModel->insert();
For basis usage, for more complex things, lets say you create a unique ref code for each user before inserting to db you could:
UserModel extends Model{
public string $refCode = '';
.....
public function insert(){
$this->refCode = generateRandomCode();
parent::inset();
}
}
So extending these functions from the base Model class you can treat them as middleware to your db calls.