Skip to content

Instantly share code, notes, and snippets.

@lightshire
Created July 15, 2014 21:23
Show Gist options
  • Select an option

  • Save lightshire/78b9b387e4488390df59 to your computer and use it in GitHub Desktop.

Select an option

Save lightshire/78b9b387e4488390df59 to your computer and use it in GitHub Desktop.
An additional helper on creating API-centric applications on laravel 4
<?php namespace Cad\System\Library;
use Sourcescript\LaravelDependencyInjector\Interfaces\DependencyInterface;
/**
* Best used w/ Fractal and LaravelDependenctInterface
*/
class Masonry
{
/**
* Sourcescript\LaravelDependencyInjector\Interfaces\DependenctInterface;
* @var DependencyInterface
*/
protected $dependencies;
/**
* BaseConstructor - Typically called by the IoC
* @param DependencyInterface $dependencies
*/
public function __construct(DependencyInterface $dependencies)
{
$this->dependencies = $dependencies;
}
/**
* Switch redirect logic to masonry for fluidity. Giving flexible
* codebase on redirecting to either as json / jsonp response or
* redirectin to a route
* @param array $message - the message to be passed or redirected
* @return Response [description]
*/
public function redirect(array $message)
{
$request = $this->dependencies->request();
$redirect = $this->dependencies->redirect();
$response = $this->dependencies->response();
$input = $this->dependencies->input();
if($request->ajax() || !isset($message['_redirect'])) {
return $response->json($message)->setCallback($input->get('callback'));
}else {
return $redirect->to($message['_redirect'])->with($message);
}
}
/**
* Message generator. Best to be compiled with a fractal counterpart.
* @param [type] $route the route for redirection
* @param string $message Notification Message
* @param boolean $success API Operation Status
* @param array $collection An array of the data returned by the
* operation
* @return array the message to be passed for redirection
*/
public function message(
$route,
$message = '',
$success = false,
array $collection = array()
)
{
return [
'message' => [
'for' => $route,
'message' => $message,
'type' => $success ? 'success' : 'error'
],
'code' => $success ? 200 : 500,
'data' => $collection ?: []
];
}
}
@srph
Copy link

srph commented Jul 22, 2014

!isset($message['_redirect']) (line 40) would be better off as !array_key_exists('redirect', $message) since isset() does more than what it appears to.

Although, the current is fine enough. This is just a suggestion to avoid certain unwanted side-effects.

@lightshire
Copy link
Author

Noted!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment