blainesch / laravel-pretty-controller by BlaineSch

35
2
0
Package Data
Maintainer Username: BlaineSch
Maintainer Contact: blainesch@gmail.com (Blaine Schmeisser)
Package Create Date: 2014-06-09
Package Last Update: 2015-06-19
Language: PHP
License: Unknown
Last Refreshed: 2024-11-19 03:13:25
Package Statistics
Total Downloads: 35
Monthly Downloads: 0
Daily Downloads: 0
Total Stars: 2
Total Watchers: 0
Total Forks: 1
Total Open Issues: 0

What?

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';