MicroFrameWork/kernel/RestController.php

62 lines
1.3 KiB
PHP
Raw Normal View History

2024-09-26 14:47:13 +03:00
<?php
namespace kernel;
use Illuminate\Database\Eloquent\Model;
use JetBrains\PhpStorm\NoReturn;
use kernel\helpers\Debug;
class RestController
{
protected Model $model;
#[NoReturn] public function actionIndex(): void
{
$request = new Request();
$page = $request->get('page') ?? 1;
$perPage = $request->get('per_page') ?? 10;
$query = $this->model->query();
if ($page > 1) {
$query->skip(($page - 1) * $perPage)->take($perPage);
} else {
$query->take($perPage);
}
$res = $query->get()->toArray();
$this->renderApi($res);
}
#[NoReturn] public function actionView($id): void
{
$model = $this->model->where("id", $id)->first();
$res = [];
if ($model){
$res = $model->toArray();
}
$this->renderApi($res);
}
#[NoReturn] public function actionDelete($id): void
{
$model = $this->model->where("id", $id)->first();
$res = [];
if ($model){
$res = $model->toArray();
}
$model->delete();
$this->renderApi($res);
}
2024-09-26 14:47:13 +03:00
#[NoReturn] protected function renderApi(array $data): void
{
header("Content-Type: application/json");
echo json_encode($data);
exit();
}
}