Laravel: Combine REST-Controllers with normal controllers and views? - php

I want to create an new app and for this purpose I've chosen laravel. So I'm also new to laravel.
I want to integrate an API from the beginning for things like browser addons or mobile apps. Of course I don't want to make it an API only app. I'll still need normal views and controllers which will handle this. Now I'm a bit confused about the proper structure. It should output the data as JSON when it's an API request, otherwise as a normal view.
What would be the best way to achieve this? All tutorials are based on API only apps which doesn't help me.
Is it good practice to make UserController.php and ApiUserController.php? Or UserController.php and a subfolder structure like API/v1.0/UserController.php? Wouldn't I repeat things often with this kind of structure? I mean often the only thing changes is the output, isn't it?
Thanks in advance!

Your API should be served on API routes, those can be in the same controller as the other user stuff but they really don't have to be.
I like to use an ApiController with all the API functions in it. In that you can implement stuff like "showUsers" and have it return User::all() or User::paginate(50). If you directly return a Model in Laravel it will output as JSON by default, which is pretty convenient.
Now for some real API goodness, I love using the API package by dingo in combination with artdarek's Laravel OAuth 2 wrapper. It providers really high quality secure API with lots of functionality, like rate limiting and scopes and all that cool stuff.
Dingo's API package
Artdarek's Laravel OAuth wrapper
You really don't want to use RESTful controllers for an API, since you probably want differently named endpoints. I like to keep all users at api/users but single users at user/USER for example. It's just what I prefer, my API should be totally customizable and routable in my opinion.

Related

Best location in Laravel for third-party API connection

I'm writing a Laravel application using one or more third-party APIs when it suddenly dawned on me. Where is the best place within the Laravel application structure to set up the API connection to consume it from my Controller? Would you use a Service or put the logic somewhere else?
$this->api = new RestApi();
->setUrl(getenv('API_REST_URL'))
->setUsername(getenv('API_USERNAME'))
->setPassword(getenv('API_PASSWORD'))
->connect();
Using services would be the better approach in Laravel, once your third party is not a direct route or content in your API, per se, it should not be in your Controller. You may want to use a Service with Guzzle.
I think the best answer is that it depends on the size of your project and what you are doing.
This post lists 3 of the most common ways. I would go with Method 3 myself (Register the API with the service container), even for simple things. It abstracts it away nicely so should work best in all situations.
https://desertebs.com/laravel/how-to-consume-external-third-party-api-in-laravel-5

Building an Restfull Api with Laravel 5

I'm planning to build an restfull api with laravel 5 for a client because they also want to make apps in the future (first ios/android, larer ios watch). For version 1.0 they only want a webversion of the site, so i'm planning to do that the traditional way with blade templating and laravel routing.
Are there good practices for combining those 2? The api routes will in some places be different then the routes i need for the 'normal' webversion, most of the services and repositories would also be the same. Output would to totally different because the api needs to return Json, where the 'normal' webversion would return Html.
Any ideas?
I would really consider not using Blade and using a front-end framework instead such as Angular. If you can get to the point where your back-end is solely serving up JSON responses, it would make your life much easier down the road.
As an added benefit, a single page app would also be much more usable on a mobile device out of the box.
You could also look into PhoneGap as well. If you have everything running on Angular, it shouldn't be too difficult to port it over to PhoneGap.

AngularJS and PHP backend

Maybe it's not a real question, rather is's a discussion. I decided to learn angular, using a simple task, build a blog system. And i have a few questions.
Lest imagine that the php app will have the MVC structure, so i have some questions:
Should i build my back-end only as RESTFUL app, and use json response\request upon the angular and php?
What about the view in php app, i should use them with ng-init?
Routing, server side or client side?
What about caching?
And the last, but not the least, where i should put the logic about data that user will input?
Can someone give me the instructions or directions, about this things, and maybe useful link's to read the articles, to combine the php and angular, or maybe i'm doing it in the wrong way?
You might want to consider this type of application as actually TWO applications.
The first is the backend, the API. You can use your PHP framework to build an API that will allow you to have data persistency, validation (business logic), etc... and forget about the front end for now, you are only building an API for the backend data.
The second part of the app is the AngularJS frontend. This includes all of the views and everything that the client sees. None of that is coming from the backend.
This allows you to use the backend API (the PHP bit) to act as the data store, with it's own validation for safety, while having the seamless user experience and basic client side validation from AngularJS.
Routing is AngularJS, as that is the actual frontend that the client is using.
Caching can be done (if needed) in the backend, your API.
Validation will happen in both the frontend and the backend, although they can be slightly different if need be.
Remember, you build the backend strictly as an API, without consideration for the frontend (as if there will be more than one app using it), so it will have it's own validation rules and logic.
Hope that helps.
I have found a very simple structure that allows me to utilize Angular with PHP and restful api's. I use Angularjs for all views. I use a restful PHP API framework called slim to facilitate the communications between Angular and the PHP models which I use Doctorine2 for.
85% of my coding is done with Angular(Views). 5% done with the API(controller) and the remaining 10% configuring business logic in the Models. Great separation of concerns and not much overhead. Simple and concise.

Architecture: API as core for a website & mobile-app

I have different questions about a full architecture idea. I hope someone with great experience could help me out because I am pretty much getting stuck in all possibilities.
I'm planning to rewrite a community website. Our customer wants to make use of native mobile apps in the future. So I will need to take this into account. Because of this I have decided to create a 100% REST API architecture based on the PHP framework Kohana. I have choosen Kohana because this makes scaling the internal API to a other server very easily without much extra effort. (Kohana threats internal url requests not as HTTP so there isn't much overhead in the beginning and can scale to HTTP with some minor code changes).
At first the API will be private, but later on we might make it public to let more services connect to us easily.
De basic REST structure is as follow:
/cats
/cats/1
/cats/1/custom
'custom' could be 'childs' for instance.
same goes for:
/ads
/bids
/users
/banners
etc..
These are perfect entities for the API because the mobile app will definitely use all this functionality.
So we can conclude the core of the website is REST. So basically I want to make the website a client of the API just like the native app in the future. This way maintenance seems much easier.
What worries me though is the fact that there is much more than this (managing uploaded files, invoicing, automails for invoicing, automails for ads and so on). Uploading files needs to go through the website to the API. Is this common practice? If I do not do this, the website would do upload logic, which makes the site no client anymore and the app itself. Hence the mobile app can't even upload and both API and website need to know the upload folder (duplicate logic).
I thought of creating the following modules:
community-api
community-website
Api seems to be the core then. But.... what about cronjobs etc? Actually they should not be part of the website, as this is just a 'client'. I feel they should interact directly with the model or API. So basically the API gets more like a gateway to the core and thought I need this:
community-core
Models
Cronjobs
Auto Mailings (part of cronjobs)
Invoices etc
community-api
Interact with models in core through HTTP
community-website
Website
Admin
The core cronjobs are a exception to the REST structure. They are the only one that can change data without going through the api. At least that was my idea because they belong in the core and API is on top of the core.
But by design that seems just wrong. Manipulating should only go through the API!
Alternative:
community-core
Models
community-api
Interact with models in core through HTTP
community business
Cronjobs
Auto Mailings (part of cronjobs)
Invoices etc
community-website
Website
Admin
This look better by design to me.
(source: mauserrifle.nl)
Main Questions
1)
Should cronjobs manipulate through the API or Core models?
2)
My invoice cronjob needs a template pretty much the style of main website of course. But if my cronjob is part of business or core it won't have knowledge of my main website. What makes sense to solve this?
3)
My website will be using mustache as a template engine. (both php and javascript can parse these templates). I thought using the api directly for ajax calls but then realized:
The site gets data from api, formats timestamps to dates (Y-m-d) for the template and then renders. If I let javascript call the api directly, javascript must have logic too (formatting). This is duplicate code! Feels like the only solution is calling the website for ajax (which calls the api and formats) and returns the formatted json. Am I right?
But.... simple calls like deleting a ad can go through the api directly (e.g. DELETE: /ads/1
I get a mix of calls....
Any better solution for this?
4)
Overall: Is my architecture too complex? Any alternatives I should consider?
I would love to hear your feedback!
Once I've heard that a good way to develop a web application is to develop an API-Centric Web Application. The thing is, to me, if you couple the main service to the public API, building an API-Centric application, you lose the whole point of developing a public API at all.
This doesn't seem logical to me.
Yes, the API and the website and what ever might come next are separate things and website should be a client to the API itself but since it will simplify things greate, I believe that you should RE-USE the domain-classes to build and base your web-site logic. This way you can use all the same code base and handle all your issues including ads, invoicing and of course file uploads with ease.
For the public API, it should be on a separate box if possible re-using the same domain classes but with different authentication methods so that whatever problem might occur, it won't affect the main service.
Your cron-jobs should only be used to fire the call through the API itself and those calls should be made on the main app (website through the API)
If you build your website without repeating-yourself, as in, using the same code as the base and wrapping the web-app around it, you won't have the issue raising in q#2.
Same thing applies for question number 3. If you wrap the website around the API, the website can use the api itself without being a separate entity.
Your architecture seems complex but if you do these things, it will be simple. ;-)
Good luck!
REST is just one way to initiate a request. Your core code that processes the request shouldn't be tightly coupled to the REST interface, or HTTP for that matter. I would advise designing your REST API as a simple mapper to an include file or something similar. Your cron could then bypass the whole REST API and just include the file directly. Separate the request interface from the code that does the actual processing.

Where to put OAuth logic?

I'm using Zend Framework in a project, and I'm creating a controller only for authentication.
In this project we'll accept that a user signs up through a account of other sites like facebook, twitter, myspace, etc.. For this we will be using OAuth. But I'm having a doubt where I should put the logic for each OAuth site related authentication? Only the facebook, for example, occupied 50 lines of code in my controller, and in this way my controllers will not be thin...
I wonder where I should put this.
Create an Zend_Auth adapter for each one of the sites, create a service only to this, what is the best way?
And sorry the poor english. :)
JF Austin has a fairly generic OAuth authentication adapter implementation that uses a Zend_Oauth_Consumer. Creating specific subclasses of this for Twitter, Facebook, etc seems to be straightforward from there. He even seems to have a Twitter adapter already. Use of the adapter is described in his blog post about it.
Alternatively, note this one by Lloyd Watkin.
Upshot: all the OAuth logic is buried inside these adapters. Your controllers can then instantiate this authentication adapter, feed it to Zend_Auth::authenticate($adapter), and then take action based upon the returned result, keeping the controller focused on the higher-level app wiring.
Your OAuth logic should live inside models as should all your buisiness logic. Your controller should be left to do is control the program flow and setup view variables for use in your view script.
Kind regards
Garry

Categories