PHP code example of timacdonald / multiformat-response-objects
1. Go to this page and download the library: Download timacdonald/multiformat-response-objects library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
timacdonald / multiformat-response-objects example snippets
class UserController
{
public function index(Request $request, CsvWriter $csvWriter)
{
// some shared logic...
$query = User::query()
->whereActive()
->whereStatus($request->query('status'));
// format check(s) and format specific logic...
if ($this->wantsCsv($request)) {
// return a CSV...
$query->each(function ($user) use ($csvWriter) {
$csvWriter->addRow($user->only(['name', 'email']));
});
return response()->download($csvWriter->file(), "Users.csv", [
'Content-type' => 'text/csv',
]);
}
// return a webpage...
$memberships = Membership::all();
return view('users.index', [
'memberships' => $memberships,
'users' => $this->query->paginate(),
]);
}
}
class UserController
{
public function index(Request $request, CsvWriter $csvWriter, )
{
$query = User::query()
->whereActive()
->whereStatus($request->query('status'));
return UserIndexResponse::make(['query' => $query]);
}
}
use TiMacDonald\MultiFormat\Response;
class UserResponse extends Response
{
public function toCsvResponse(CsvWriter $writer)
{
$this->query->each(function ($user) use ($writer) {
$writer->addRow($user->only(['name', 'email']));
});
return response()->download($writer->file(), "Users.csv", [
'Content-type' => 'text/csv',
]);
}
public function toHtmlResponse()
{
$memberships = Membership::all();
return view('users.index', [
'memberships' => $memberships,
'users' => $this->query->paginate(),
]);
}
}
class UserController
{
public function index()
{
//...
return UserResponse::make(['query' => $query])
->withDefaultFormat('csv');
}
}
class UserResponse extends Response
{
protected $defaultFormat = 'csv';
// ...
}
'audio/mpeg' => ['mpga', 'mp2', 'mp2a', 'mp3', 'm2a', 'm3a'],
class UserController
{
public function index()
{
//...
return UserResponse::make(['query' => $query])
->withFormatOverrides([
'audio/mpeg' => 'mp3',
]);
}
}
class UserResponse extends Response
{
protected $formatOverrides = [
'audio/mpeg' => 'mp3',
];
// ...
}
Route::get('users{extension?}', [
'as' => 'users.index',
'uses' => 'UserController@index',
// this is what we need to add...
'where' => [
'extension' => '^\.(pdf|csv|xlsx)$',
],
]);
class UserResponse extends Response
{
/**
* @var \Illuminate\Database\Eloquent\Builder
*/
private $query;
public function __construct(Builder $query)
{
$this->query = $query;
}
}
//...
return new UserResponse($query);