added responsable class to index
This commit is contained in:
@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Abstracts\Http;
|
||||
|
||||
use App\Abstracts\Http\Response;
|
||||
use App\Traits\Jobs;
|
||||
use App\Traits\Relationships;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
@ -99,4 +100,25 @@ abstract class Controller extends BaseController
|
||||
|
||||
return new LengthAwarePaginator($items->forPage($page, $perPage), $items->count(), $perPage, $page, $options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a response based on request type like HTML, JSON, or anything else.
|
||||
*
|
||||
* @param string $view
|
||||
* @param array $data
|
||||
*
|
||||
* @return \Illuminate\Http\Response
|
||||
*/
|
||||
public function response($view, $data = [])
|
||||
{
|
||||
$class_name = str_replace('Controllers', 'Responses', (new \ReflectionClass($this))->getName());
|
||||
|
||||
if (class_exists($class_name)) {
|
||||
$response = new $class_name($view, $data);
|
||||
} else {
|
||||
$response = new class($view, $data) extends Response {};
|
||||
}
|
||||
|
||||
return $response;
|
||||
}
|
||||
}
|
||||
|
55
app/Abstracts/Http/Response.php
Normal file
55
app/Abstracts/Http/Response.php
Normal file
@ -0,0 +1,55 @@
|
||||
<?php
|
||||
|
||||
namespace App\Abstracts\Http;
|
||||
|
||||
use Illuminate\Contracts\Support\Responsable;
|
||||
use Illuminate\Support\Arr;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
abstract class Response implements Responsable
|
||||
{
|
||||
protected $accepts = ['json', 'rss'];
|
||||
|
||||
protected $view;
|
||||
|
||||
protected $data;
|
||||
|
||||
public function __construct($view, $data)
|
||||
{
|
||||
$this->view = $view;
|
||||
$this->data = $data;
|
||||
}
|
||||
|
||||
public function toJson()
|
||||
{
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'error' => false,
|
||||
'data' => Arr::first($this->data),
|
||||
'message' => '',
|
||||
]);
|
||||
}
|
||||
|
||||
public function toHtml()
|
||||
{
|
||||
return view($this->view, $this->data);
|
||||
}
|
||||
|
||||
public function toResponse($request)
|
||||
{
|
||||
foreach ($this->accepts as $accept) {
|
||||
$request_method = 'expects' . Str::studly($accept);
|
||||
$response_method = 'to' . Str::studly($accept);
|
||||
|
||||
if (!method_exists($request, $request_method) || !method_exists($this, $response_method)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($request->{$request_method}()) {
|
||||
return $this->{$response_method}();
|
||||
}
|
||||
}
|
||||
|
||||
return $this->toHtml();
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user