Created
October 31, 2017 04:22
-
-
Save ihsaneddin/0cf3ec2ab9e80f650d42fbe8d15845ba to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
trait Responder | |
{ | |
# | |
#params options value must be closure | |
# | |
protected function respondTo(array $options=array()) | |
{ | |
$contentType= $this->requestContentType(); | |
if ( array_key_exists($contentType, $options) && is_callable($options[$contentType])) return $options[$contentType](); | |
return null; | |
} | |
# | |
# get request content type | |
# | |
protected function requestContentType(){ | |
$mimes = array( 'application/json' => 'json', 'application/javascript' => 'js', 'text/html' => 'html', | |
'text/xml' => 'xml', 'application/pdf', 'text/csv' => 'csv'); | |
if (array_key_exists(request()->header('content-type'), $mimes)) return $mimes[request()->header('content-type')]; | |
return 'html'; | |
} | |
} | |
## contoh buat di controller | |
public function index(Request $request){ | |
$links = $this->resources::all(); | |
return $this->respondTo( | |
array('html'=> function() use ($links) | |
{ | |
return $this->layout()->nest('content', $this->view, array('links'=> $links)); | |
}, | |
'json' => function() use ($links) | |
{ | |
return Response::json($links, 200); | |
} | |
) | |
); | |
} | |
### contoh di handler.php | |
public function render($request, Exception $exception) | |
{ | |
return $this->respondTo( | |
array('html'=> function() use ($request, $exception) | |
{ | |
return parent::render($request, $exception); | |
}, | |
'json' => function() use ($request, $exception) | |
{ | |
$statusCode = 500; | |
if ($exception instanceof ModelNotFoundException) | |
{ | |
$statusCode= 404; | |
} | |
return Response::json(array("message" => $exception->getMessage()), $statusCode); | |
} | |
) | |
); | |
} | |
### contoh json request return html | |
public function create() | |
{ | |
$this->resources = array('car' => $this->resource, | |
'categories' => Category::ClassListSelectInput(), | |
'carList' => Car::carListSelectOptions() | |
); | |
return $this->respondTo( | |
array('html'=> function() | |
{ | |
$this->layout->nest('content', $this->view, $this->resources); | |
}, | |
'js' => function() | |
{ | |
$form = View::make($this->form, $this->resources)->render(); | |
return View::make('admin.shared.modal', array('body' => $form))->render(); | |
} | |
) | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment