So am basically building a restful client with laravel that will not have a database. So if anyone has any ideas on how to structure this, I would be very grateful.
Cheers
Laravel is an opinionated PHP framework.
Laravel Create Model is an MVC based PHP system. In the MVC architecture, 'M' stands for 'Model'. A model is used as a way for questioning data to and from the table within the database. Laravel gives a basic way to do that using Eloquent ORM where each table incorporates a Model to interact with it.
Laravel provides a convenient way to create Restful APIs via resourceful controllers. Create a route for the resourceful controller in routes/api.
I think that the more generic and robust design for your app is the MVC pattern like a standard Laravel app. In fact the only difference is that the model layer will not interact with a database but with an API.
You will have to forget Eloquent model and build your own model layer with the classic Object Oriented practices (constructor, accessors...). Then you will be able to deal with objects in your controller and not with an API. If you want to build something enough generic to be reused you can adopt the same syntax as Eloquent and write models like that :
<?php
class User {
protected $url = "http://myapi.com/users/"
protected $id;
protected $name;
public function save()
{
$data = json_encode(array(
'id' => $this->id,
'name' => $this->name,
))
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_PUT, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
return true;
}
}
Then you will be able to call $user->save();
with the exact same behavior that an Eloquent model. Of course, a lot of improvements and generalisation (why not a super class named EloquentAPI...) are needed but you can see the idea. If the job is well done with methods all()
, find()
, save()
and few others implemented, you could switch between a database or a web service implementations easily. The other big interest of this approach is to clean up your controllers and let all the curl's mess in a separate layer.
The second option is to forget the model layer and directly call your REST API in your controllers. It could be a good idea if your app is small and don't need to be scalable but, be careful, if you do that the maintenance of your app could be painful, for example if there is changes in the REST API.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With