blainesch/laravel-pretty-controller

There is no license information available for the latest version (0.0.1) of this package.

0.0.1 2014-06-09 04:37 UTC

README

Build Status

This library provides helpful content negotiations. For instance if you ask for json back from a typical laravel website you'd still get html back. I carefully look at the Accept header and type (.json for instance) to best determine what media type to render.

What does this mean? It means your controller actions are cleaner, all you do is return values!

class UserController extends BaseController {
	public function show()
	{
		return View::make('user.show')->with([
			'name' => 'BlaineSch',
		]);
	}
}

Now, let's respond to multiple content types and prettify our controller!

class UserController extends BaseController {
	public function showAction()
	{
		return ['name' => 'blainesch'];
	}
}

Installation

Composer

'require': {
	"blainesch/laravel-pretty-controller": "0.0.1"
}

Update Controller and add CoreController values in your app/config/app.php file.

'aliases' => [
	// ...
	'Controller'      => 'Blainesch\LaravelPrettyController\Action\PrettyController',
	'CoreController'  => 'Illuminate\Routing\Controller',
	// ...
]

Register your media types

Create a bootstrap/media.php

<?php

use Blainesch\LaravelPrettyController\Http\MediaType;

MediaType::add('html', [
	'conditions' => [
		'accept' => [
			'text/html',
			'*/*',
		],
	],
	'encode' => function($request, $response) {
		$class = strtolower(str_replace('Controller', '', $request['controller']));
		return \View::make("{$class}.{$request['method']}")->with($response);
	},
]);

MediaType::add('json', [
	'conditions' => [
		'type' => 'json',
		'accept' => [
			'application/json',
			'application/x-json',
		],
	],
	'encode' => function($request, $response) {
		return json_encode($response);
	},
]);

Include this file in bootstrap/autoload.php below composer autoloader

require __DIR__.'/media.php';