There are several questions on here that are similar, but not that are really providing exactly what I need.
I am creating a simple pet project in Laravel 5.3 that uses https://xboxapi.com/ to pull in JSON of Xbox Games. At first I was going to create a Game model, but I understand that because I am using 3rd party, I really won't be pulling any data in from my own DB and there's really no need to use Eloquent ORM at this time.
What is the "Laravel way" to do this? I can use Guzzle to hit the API, and create methods to get game by title, get game by publisher, etc. I guess what I am asking is where does this go within my app's file structure? I understand there may be no right or wrong answer. Really just looking for some insight into improving my OOP concepts.
Edit
Should I just put this into a GamesController? I don't want to have Guzzle in my controller, right?
Or should I actually create a Game class that extends the Eloquent model, and then overwrite methods like ::all() and ::find() to hit the API rather than the applications database?
Thanks ahead of time!
Yes. Use Guzzle. The PSR-7 spec has implemented 3 RFC's that dictate how HTTP request objects should be handled.
Guzzle does have PSR-7 support, you can see the git repository here.
For API based CRUD requests, create a new Controller namespace and move your API logic there. Consume your own API's internally if you need through these external end points:
artisan make:controller Api\\UserController
Now update your RouteServiceProvider, and add a new declaration:
private $api_namespace = 'App\Http\Controllers\Api`.
Now update your mapApiRoutes() and change your namespace:
'namespace' => $this->api_namespace
Now all of your API requests should route to Api\Controllers.
Related
Currently building an API that pulls data from another API.
I'm just a little unsure about how I should represent some data considering the whole skinny/fat model/controller argument and I haven't been able to find a clear answer so I was hoping for a discussion on this here.
As Models represent interactions with data it feels like my calls be mapped into a model using something like Fractal or Jenssengers "Laravel Model".
As currently I have actions in my controller that send send requests, but it feels like this is a bit too much responsibility for a controller.
So I just wanted some opinions on where I should place this logic in regards to a Laravel project!
Thanks
EDIT:
From further research it looks like the repository design pattern may be a possible solution!
Repositories Simplified
Using Repository Pattern In Laravel 5
Neither method is particularly a great solution. Really, a Controller is responsible for handling the HTTP requests and your models are representations of your business domain. So where does third-party data fit into this?
Well, the data itself should probably be represented by a model. However, the method of getting the data from the third party provider should really be delegated to a service provider that you can then easily switch out to work with different apis and thus decoupling yourself from a single provider (easiest example would be payment gateways, having all of your logic hard coded in your Controller for a Paypal integration would make it extremely difficult to then later add a second payment option).
Take the following example; let's say you have an application that provides a user with the latest results for their favourite football teams.
Your application could have the following endpoints:
/team/{team}/players
/team/{team}/fixtures
/team/{team}/results
These could map to the following controller methods:
PlayerController#getPlayersInTeam($team);
FixturesController#getFixturesForTeam($team);
ResultsController#getLatestResultsForTeam($team);
Notice there are three different controllers, rather than one single controller. This way you can assign a controller to the type of model you're expecting to return to the user.
Now obviously, you shouldn't do your API calls within each controller. But, why would you then do it within your model? The term 'Skinny controllers, fat models' is such an anti-pattern that it really does a lot more harm than good.
Why not use a service that is solely responsible for getting data from the API for your models?
interface FootballTeamData
{
public function getPlayersInTeam(Team $team);
public function getTeamFixtures(Team $team);
public function getTeamResults(Team $team);
}
Now, you can implement this contract and easily switch the way that you get your data from third parties without having to touch your models - which is your business domain, and therefore shouldn't be so highly coupled with the third party API.
You're also now benefiting from skinny controllers, and skinny models. There's no reason why a class can't exist that has just a few lines of code, neither should be fat.
Good luck!
I have an existing app that was built on the Yii Framework for managing wine cellars. I used the standard Gii utility to create the initial CRUD controllers/models/views. I've significantly modified the code to meet my needs for navigation, look & feel and functionality. I'm now beginning the design for a companion mobile (android) app that will need to consume and create some of the data (get a list of wines in my cellar - GET, add a new wine to the cellar - POST) that can be used while out shopping/wine-tasting. I don't intend to expose all the models/controller options as web services, only a specific set of functions.
My question is really a design issue. Should I add the API methods to the existing CRUD controllers or should I create a new "API Controller" for each of the models (or a single apiController is another option I've seen)? My thinking is separate API controllers. This would allow me to update/deploy API specific changes more easily and to logically compartmentalize that interface. This API will need to be authenticated and I will probably implement OAuth in a future release.
BTW, I've looked at the RESTFullYii extension and I haven't been able to grok exactly how it works. I'd really love to see a working example app not just code snippets.
I suggest you to create a new controller. For example ApiController. You put all your actions such as actionAddWine. So you can call this action like:
http://example.com/index.php?r=api/addWine
The advantage of doing this, is that you have all your models, and you just need to interact with your modes via REST. In order to create a simple REST api you can check the following document which is really simple explained.
How-To: Create a REST API
If you do like the mentioned article, You can send the response to client simply using _sendResponse() method.
Another thing is to do authentications and similar things which can is readily attainable using your controller's init() method.
Another way is to create a module for your application. If you want to completely divide your API from your other codes you can create a module. You can create modules with GII. The advantage of module is that you can separate your sections. For example your actions will be:
http://example.com/index.php?r=api/wine/add
in above url you are calling an action in api module, and wine controller which its name is add.
Note that you can use your models in module by importing them.
Yes, go for separate controllers. You may even want to set up a separate application that shares some of your apps models and config but also allows for a more separate feel.
Also with planning how you will version your Api, as it is likely to need to change down the road while still needing to support your older Android app
I need to send a push message from Urban Airship. To do this I have to send an API request from CakePHP.
My question: where should i put the code for the API request in CakePHP? In the model or in the controller? Where is the correct place for this?
I follow Neil Crookes' idea of keeping the logic in the datasource. An API is really just a datasource, after all. Then, models are introduced as the various endpoints the API has. For example, I have a Stripe plugin that follows this model. A StripeCustomer model then has a $path variable that the datasource uses as the endpoint.
This model has several benefits:
API calls are integrated with the ORM - so they look like regular model finds and saves
You can utilize built in validation, callbacks, behaviors, etc.
Very DRY and therefore easy to debug and test
I am developing RESTful with php. Currently I have started coding with MVC design pattern. In which the view files are acting as an interface. An interface which isn't showing any graphical UI but it has all the request handling logic.
Now, my question is the way I am coding is correct or there is a better way to create RESTful api in php?
My inspiration is based on JavaEE application model. In which we have Entity classes as model, Java beans as controllers and Remote Interface is the the list of method which gets called from client (kind of a view).
Am I on right track?
A good example for building a RESTful API in a PHP based MVC framework can be found at http://www.chrisdanielson.com/2009/09/02/creating-a-php-rest-api-using-the-zend-framework/.
This example extends a class in Zend Framework called the Zend_Rest_Controller which simplifies this process. You can have a look at the source code to see how they do it and if it gives you an ideas on how to make your own implementation.
To answer your question though, you should have controllers acting as the interface. So if you send a POST request to myapp.com/comment (where comment is the controller), it knows you are trying to add a new comment. If you send a GET request to the same URL, it knows you want all of the comments, and if you send a GET request to myapp.com/comment/4 it knows you want to get the comment with ID 4. Your views should have nothing to do with the internal functionality of your API.
You can use any existing RESTful PHP MVC framework, like Yii or Kohana both are very light and natively support RESTful applications.
For your existing application, MVC model states that all the requests and logic handling should be done by the Controllers not the views. Things are usually done in one of two ways here:
(1) Controller has a special method to respond to each type of requests and acts differently As seen in RubyOnRails (mainly at the end of each controller action)
respond_to do |format|
format.html
format.xml { render :xml => #events}
format.json { render :json => #events}
end
(2) Controller detects the current requested format and changes that entire theme/layout to, say, a JSON theme (All layouts/views receive the same data). This is my current implementation and it goes like:
$format is any of [html,json,xml] (detected from url suffix)
$controller->layout = "$format";
$controller->render($viewFile, $object);
view file in HTML Layout
<div id='model>
<h1><?=$object->title?></h1>
<p><?=$object->description?></p>
</div>
View file in JSON layout
echo json_encode($object);
View file in XML layout
/** Loop and build XML tree */
I did a bunch of webinars on API Facade Design Patterns. Hope you will find the concepts useful irrespective of the underlying technology you use to implement it. Please can find it here
http://youtu.be/n8B-K3iJ7b4
http://youtu.be/MRxTP-rQ-S8
http://youtu.be/aJBhVm4BbCI
Apigility is a Zend Framework 2 based project designed soley for the purpose of creating REST and RPC services.
https://apigility.org/
Out of the box you're given an easy way to get started with MySQL and OAuth2 for authentication.
Has anyone implemented something similar?
The problem I have is the fact that we're not using REST. The current plan is the following:
Create a controller called sync($modelName, $action) and throw all requests at that.
Create an interface called "syncable" and force models to implement it.
How it works:
GET http://localhost/sync?modelName=User&action=update&first_name=Peeter
This will look for a model named UserModel that implements the syncable interface. If found, update its parameters and update(); to db.
The syncable interface is to enable per-record actions. E.g. "Only record owner can update this record" or "Only admin can delete this record".
I wrote a fully function REST API framework into symfony 1.4. It supports JSON and JSONP. I've open sourced it, so you're welcome to use it. We're using it in production with a lot of traffic, so it's pretty stable and we've had great feedback from the consumers. It's really flexible and very fast to write API methods. We also have a documentation page that allows you to make test queries. It's one of the best API docs I've seen.
https://github.com/homer6/blank_altumo
See this (below) for an example of an API controller. This contoller only shows GET, but PUT, POST and DELETE are fully implemented.
https://github.com/homer6/blank_altumo/blob/master/htdocs/project/apps/api/modules/system_event/actions/actions.class.php
If you need help getting it going, I'm willing to spend a few minutes to explain its design or get it working for you.
Hope that helps...
I had the same issue with an app I'm working on, so I implemented a ChangeTracker that subscribes to my observable properties, and tracks any changes made. Then, at any later point, I can call something like:
viewModel.changeTracker.commit();
which is responsible for massaging my change objects into a format that the server understands, and ships it off for processing.
Here is a little fiddle demonstrating the idea. http://jsfiddle.net/ggoforth/pCX8c/2/
Note: I've had a string of days where I've been working till 3am so there may be a better way of doing this, and I'm just to exhausted to realize it :)