How Follow the Don’t Repeat Yourself Principle When Consuming My Own Laravel API?

I’m actually tinkering with the same idea and it’s pretty neat. With Laravel you do have the ability to make internal requests (some might refer to this as HMVC, but I won’t). Here’s the basics of an internal request.

$request = Request::create('/api/users/1', 'GET');

$response = Route::dispatch($request);

$response will now contain the returned response of the API. Typically this will be returned a JSON encoded string which is great for clients, but not that great for an internal API request. You’ll have to extend a few things here but basically the idea is to return the actual object back through for the internal call, and for external requests return the formatted JSON response. You can make use of things like $response->getOriginalContent() here for this kind of thing.

What you should look at doing is constructing some sort of internal Dispatcher that allows you to dispatch API requests and return the original object. The dispatcher should also handle malformed requests or bad responses and throw exceptions to match.

The idea itself is solid. But planning an API is hard work. I’d recommend you write up a good list of all your expected endpoints and draft a couple of API versions then select the best one.

Leave a Comment