Skip to content

Instantly share code, notes, and snippets.

@macghriogair
Created March 20, 2016 23:16
Show Gist options
  • Save macghriogair/d19d52a4c931cd8a9a16 to your computer and use it in GitHub Desktop.
Save macghriogair/d19d52a4c931cd8a9a16 to your computer and use it in GitHub Desktop.
Lumen ApiController base
<?php
namespace App\Http\Controllers;
use Laravel\Lumen\Routing\Controller;
use Symfony\Component\HttpFoundation\StreamedResponse;
class ApiController extends Controller
{
/**
* Http Statuscode
* @var integer
*/
protected $statusCode = 200;
/**
* Returns a Json response.
*
* @param mixed $data
* @param array $headers
* @return Illuminate\Http\Response
*/
public function respond($data, $headers = [])
{
return response()->json($data, $this->getStatusCode(), $headers);
}
/**
* Outputs a file stream to the browser.
*
* @param callable $callback
* @param array $headers
* @return null
*/
protected function respondWithStream(callable $callback, array $headers)
{
$response = new StreamedResponse($callback, $this->getStatusCode(), $headers);
$response->send();
}
/**
* Returns 404 Not found
*
* @param string $message
* @return Illuminate\Http\Response
*/
public function respondNotFound($message = 'Not found!')
{
return $this->setStatusCode(404)->respondWithError($message);
}
/**
* Returns 500 Server Error
* @param string $message
* @return Illuminate\Http\Response
*/
public function respondInternalError($message = 'Internal Error!')
{
return $this->setStatusCode(500)->respondWithError($message);
}
/**
* Returns an error message with the response.
*
* @param string $message
* @return Illuminate\Http\Response
*/
public function respondWithError($message)
{
return $this->respond([
'error' => [
'message' => $message,
'status_code' => $this->getStatusCode()
]
]);
}
/**
* Gets the value of statusCode.
*
* @return mixed
*/
public function getStatusCode()
{
return $this->statusCode;
}
/**
* Sets the value of statusCode.
*
* @param mixed $statusCode the status code
*
* @return self
*/
protected function setStatusCode($statusCode)
{
$this->statusCode = $statusCode;
return $this;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment