-
paliz Member
  
-
Posts: 236
Threads: 19
Joined: Oct 2020
Reputation:
1
09-26-2021, 09:02 AM
(This post was last modified: 09-26-2021, 09:33 AM by paliz.)
they access data via restful api is call get request and its needs Design filter search sort pagination too
i developed library to do that for us
before explain code first open this link it about aggregation functions
https://forum.codeigniter.com/thread-801...#pid390293
lets start see codes then go bellow
PHP Code: quer
<?php
namespace Modules\Shared\Interfaces;
use Modules\Shared\Libraries\UrlQueryParam;
interface UrlQueryParamInterface {
//--------------------------------------------------------------------
/** * get key * * @param array $dataMap * */
public function dataMap(array $dataMap): void;
//--------------------------------------------------------------------
/** * Get value. * * * @param string $key * @param string $value * @param string $function * @param string $sign * @param string|null $joinWith * @return string */ public function encodeQueryParam(string $key, string $value, string $function, string $sign, string $joinWith = ''): string;
//--------------------------------------------------------------------
/** * Get value. * * * * @return UrlQueryParam * */ public function decodeQueryParam(): UrlQueryParam;
/** * Get value. * @param string $append * */ public function setTableName(string $append): UrlQueryParam;
/** * Get value. * @return int */ public function getForeignKey(): int;
/** * Get value. * @param array|null $defaultPipeLine * @return array */ public function getPipeLine(?array $defaultPipeLine = null): array; }
PHP Code: <?php namespace Modules\Shared\Libraries;
use CodeIgniter\HTTP\RequestInterface; use Modules\Shared\Interfaces\UrlQueryParamInterface;
class UrlQueryParam implements UrlQueryParamInterface {
private const Point = "."; private int $limit; private int $offset; private string $range; private int $page; private string $filed; private array $q; private string $order; private string $sort; private int $foreignKey; private string $tableName; private array $pipeLine;
public function __construct(RequestInterface $request) {
$this->range = $request->getGet('range') ?? '1to10'; $this->sort = $request->getGet('sort') ?? 'id'; $this->order = $request->getGet('order') ?? 'desc'; $this->page = $request->getGet('page') ?? 1; $this->limit = $request->getGet('limit') ?? '10'; $this->offset = $request->getGet('offset') ?? '0'; $this->filed = $request->getGet('filed') ?? ''; $this->foreignKey = $request->getGet('foreignKey') ?? 0; $this->q = []; isset($_GET['q']) ? parse_str($request->getGet('q'), $this->q) : $this->q = []; $this->tableName = ''; $this->pipeLine = [];
}
/** * @param array $dataMap */ public function dataMap(array $dataMap): void {
$object = []; $isEqual = false; foreach ($this->q as $key => $value) {
foreach ($dataMap as $needle => $hook) { if ($needle == $key) {
$object[$hook] = $value; $isEqual = true; } } if ($isEqual == true) { $isEqual = false; } else { $object[$key] = $value; }
} $this->q = $object; }
/** * @return array */ public function decodeQueryParam(): UrlQueryParam { $whiteList = ['whereIn', 'whereNotIn', 'orWhereIn', 'orWhereNotIn', 'orHavingIn', 'havingNotIn'];
$temp = []; $object = null; $counter = 0; foreach ($this->q as $key => $value) { $object = json_decode($value);
if (in_array($object->fun, $whiteList)) { if (isset($object->jin)) { $temp['key'] = $object->jin . self::Point . $key; } else { $temp['key'] = $this->tableName . $key;
} $temp['value'] = $object->val; } else if (isset($object->sgn) && !empty($object->sgn) && is_array($object->sgn)) {
foreach ($object->sgn as $sgn) { $key = $key . ' ' . $sgn;
if (isset($object->jin)) { $temp[$object->jin . self::Point . $key] = $object->val[$counter]; } else { $temp[$this->tableName . $key] = $object->val[$counter]; } $counter++; } } else if (isset($object->sgn) && !empty($object->sgn) && is_string($object->sgn)) {
$key = $key . ' ' . $object->sgn;
if (isset($object->jin)) { $temp[$object->jin . self::Point . $key] = $object->val; } else { $temp[$this->tableName . $key] = $object->val; } } else {
if (isset($object->jin)) { $temp[$object->jin . self::Point . $key] = $object->val; } else { $temp[$this->tableName . $key] = $object->val; } } $counter = 0; $this->pipeLine[str_replace(' ', '', $object->fun)] = $temp; } return $this; }
private function selectFields(string $query): string { if ($this->filed != '') { return $this->filed; } else { return $query; }
}
/** * @return int */ public function getForeignKey(): int { return $this->foreignKey; }
/** * @param string $append */ public function setTableName(string $append): UrlQueryParam { $this->tableName = $append . self::Point; $this->tableName = $str = str_replace(' ', '', $this->tableName); return $this; }
public function encodeQueryParam(string $key, string $value, string $function, string $sign, string $joinWith = ''): string {
$data = ['fun' => $function, 'val' => $value, 'sgn' => $sign]; if (strlen($joinWith) > 0) $data['jin'] = $joinWith;
return http_build_query(array($key => [json_encode($data)]));
}
public function getPipeLine(?array $defaultPipeLine = null): array {
$this->pipeLine['select'] = (isset($defaultPipeLine['select'])) ? $this->selectFields($defaultPipeLine['select']) : $this->tableName . '*'; if ((isset($defaultPipeLine['join']))) { $this->pipeLine['join'] = $defaultPipeLine['join'];
} if (!empty($defaultPipeLine)) { foreach ($defaultPipeLine as $key => $value) { if ($key != 'select' && $key != 'join' && array_key_exists($key, $this->pipeLine)) {
$this->pipeLine[$key] = array_merge($this->pipeLine[$key], $value); } } }
$this->pipeLine['offset'] = $this->offset; $this->pipeLine['limit'] = $this->limit; $this->pipeLine['page'] = $this->page; $this->pipeLine['order'] = $this->order; $this->pipeLine['sort'] = strlen($this->tableName) ? $this->tableName . $this->sort : $this->sort;
return $this->pipeLine; }
}
PHP Code: <?php
namespace Modules\Shared\Controllers;
/** * Class BaseController * * BaseController provides a convenient place for loading components * and performing functions that are needed by all your controllers. * Extend this class in any new controllers: * class Home extends BaseController * * For security be sure to declare any new methods as protected or private. * * @package CodeIgniter */
use CodeIgniter\HTTP\RequestInterface; use CodeIgniter\HTTP\ResponseInterface; use CodeIgniter\RESTful\ResourceController; use Modules\Auth\Config\Services; use Myth\Auth\AuthTrait; use Psr\Log\LoggerInterface; use Modules\Shared\Interfaces\UrlQueryParamInterface; use Modules\Shared\Libraries\UrlQueryParam;
class ApiController extends ResourceController { use AuthTrait;
protected $format = ""; public object $userObject; public UrlQueryParamInterface $urlQueryParam;
/** * An array of helpers to be loaded automatically upon * class instantiation. These helpers will be available * to all other controllers that extend BaseController. * * @var array */ protected $helpers = [ 'cookie', 'url', 'from', 'filesystem', 'text', 'shared' ];
/** * Constructor. * * @param RequestInterface $request * @param ResponseInterface $response * @param LoggerInterface $logger */
/** * @var string * Holds the session instance */ protected $session;
public function __construct() {
$this->userObject = (object)[]; }
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger) { // Do Not Edit This Line parent::initController($request, $response, $logger);
$this->urlQueryParam = new UrlQueryParam($request);
$requestWithUser = Services::requestWithUser(); $this->userObject = $requestWithUser->getUser();
}
}
Quote:PHP Code: <?php namespace Modules\Common\Controllers;
use CodeIgniter\HTTP\ResponseInterface; use Modules\Common\Config\Services; use Modules\Shared\Controllers\ApiController;
class User extends ApiController {
/** * index function * @method : GET */ public function index() {
$usersEntity = new \Myth\Auth\Entities\User(); $this->urlQueryParam->dataMap($usersEntity->getDataMap());
$userService = Services::userService(); $findAllData = $userService->index($this->urlQueryParam);
return $this->respond([ 'data' => $findAllData['data'], 'pager' => $findAllData['pager'] ], ResponseInterface::HTTP_OK, lang('Shared.api.receive'));
}
/** * show function * @method : GET with params ID */ public function show($id = null) { $userService = Services::userService(); $findOneData = $userService->show($id); return $this->respond([ 'data' => $findOneData['data'], 'pager' => $findOneData['pager'] ], ResponseInterface::HTTP_OK, lang('Shared.api.receive'));
}
/** * create function * @method : POST */ public function create() {
// Validate here first, since some things, // like the password, can only be validated properly here. // strong password didint work custom validation strong_password // password=> strong_password $rules = [ 'username' => 'required|alpha_numeric_space|min_length[3]|is_unique[users.username]', 'email' => 'required|valid_email|is_unique[users.email]', 'password' => 'required', 'first_name' => 'if_exist|required|max_length[255]', 'last_name' => 'if_exist|required|max_length[255]', 'phone' => 'if_exist|required|max_length[11]', 'group' => 'required|alpha', ];
if (!$this->validate($rules)) {
return $this->respond([ 'error' => $this->validator->getErrors(), ], ResponseInterface::HTTP_NOT_ACCEPTABLE, lang('Shared.api.validation'));
}
// Save the user
$userEntity = new \Myth\Auth\Entities\User((array)$this->request->getVar()); $userEntity->activate()->disableStatus();
$userService = Services::userService();
$userService->create($userEntity);
return $this->respond([
], ResponseInterface::HTTP_CREATED, lang('Shared.api.save'));
}
/** * update function * @method : PUT or PATCH */ public function update($id = null) { //model
$json = $this->request->getJSON(); if (!isset($id)) { $id = $json->id; }
// Validate here first, since some things, // like the password, can only be validated properly here. // strong password didint work custom validation strong_password // password=> strong_password $rules = [
'first_name' => 'if_exist|required|max_length[255]', 'last_name' => 'if_exist|required|max_length[255]', 'phone' => 'if_exist|required|max_length[11]', 'group' => 'if_exist|required|alpha', 'status' => 'if_exist|required', ];
if (!$this->validate($rules)) { return $this->respond([ 'error' => $this->validator->getErrors(), ], ResponseInterface::HTTP_NOT_ACCEPTABLE, lang('Shared.api.validation'));
}
$userEntity = new \Myth\Auth\Entities\User((array)$this->request->getVar());
$userService = Services::userService();
$userService->update($id, $userEntity);
return $this->respond([ ], ResponseInterface::HTTP_OK, lang('Shared.api.update'));
}
/** * edit function * @method : DELETE with params ID */ public function delete($id = null) {
$userService = Services::userService(); $userService->delete($id); return $this->respond([ ], ResponseInterface::HTTP_OK, lang('Shared.api.remove'));
}
}
PHP Code: <?php namespace Modules\Common\Services;
use CodeIgniter\HTTP\ResponseInterface; use Modules\Common\Libraries\CustomFile; use Modules\Shared\Interfaces\UrlQueryParamInterface; use Modules\Shared\Libraries\MainService;
class UserService extends MainService { private \Myth\Auth\Models\UserModel $userModel; private \Myth\Auth\Authorization\GroupModel $groupModel; private CustomFile $cfs;
public function __construct() { $this->userModel = new \Myth\Auth\Models\UserModel(); $this->groupModel = new \Myth\Auth\Authorization\GroupModel(); $this->cfs = new CustomFile(); }
/** * index function * @method : GET * @param UrlQueryParamInterface $urlQueryParam * @return array */ public function index(UrlQueryParamInterface $urlQueryParam) {
$pipeLine = [ 'select' => ' users.id, users.email, users.username , users.first_name as firstName, users.last_name as lastName, users.image, users.gender, users.birthday, users.country, users.city, users.address, users.phone, users.status_message as statusMessage, users.status, users.active , users.created_at as createdAt, users.updated_at as updatedAt, users.deleted_at as deletedAt', 'auth_groups.name as group', 'join' => [ ['table' => 'auth_groups_users', 'condition' => 'auth_groups_users.group_id = auth_groups.id', 'mode' => 'right'], ['table' => 'users', 'condition' => 'auth_groups_users.user_id = users.id', 'mode' => 'left'] ] ]; $pipeLine = $urlQueryParam->setTableName('users')->decodeQueryParam()->getPipeLine($pipeLine);
return $this->groupModel->aggregatePagination($pipeLine);
}
/** * show function * @method : GET with params ID * @param $id * @return array */ public function show($id) { if (is_null($id)) $this->httpException(lang('Shared.api.validation'), ResponseInterface::HTTP_NOT_FOUND);
$group = $this->groupModel->getGroupsForUser($id); $result = $this->groupModel->select(' users.email, users.username , users.first_name as firstName, users.last_name as lastName, users.image, users.gender, users.birthday, users.country, users.city, users.address, users.phone, users.status_message as statusMessage, users.status, users.active , users.created_at as createdAt, users.updated_at as updatedAt, users.deleted_at as deletedAt, auth_groups.name as group') ->join('auth_groups_users', 'auth_groups_users.group_id = auth_groups.id', 'left') ->join('users', 'auth_groups_users.user_id = users.id', 'left') ->where('auth_groups.id', $group[0]['group_id']) ->where('users.id', $id) ->paginate(1, 'default');
if (is_null($result)) $this->httpException(lang('Shared.api.exist'), ResponseInterface::HTTP_NOT_FOUND);
$data = [ 'data' => $result, 'pager' => $this->groupModel->pager->getDetails() ];
return $data;
}
/** * create function * @method : POST * @param \Myth\Auth\Entities\User $entity */ public function create(\Myth\Auth\Entities\User $entity) { if (is_null($entity)) $this->httpException(lang('Shared.api.validation'), ResponseInterface::HTTP_NOT_FOUND);
$this->userModel->withGroup($entity->toArray()['group']);
if (!$this->userModel->save($entity)) { helper('shared'); $this->httpException(lang('Shared.api.reject'), ResponseInterface::HTTP_BAD_REQUEST, serializeMessages($this->userModel->errors()));
}
}
/** * update function * @method : PUT or PATCH * @param $id * @param \Myth\Auth\Entities\User $entity */ public function update($id, \Myth\Auth\Entities\User $entity) { if (is_null($entity)) $this->httpException(lang('Shared.api.validation'), ResponseInterface::HTTP_NOT_FOUND);
$isExist = $this->userModel->where('id', $id)->first();
if (is_null($isExist)) $this->httpException(lang('Shared.api.exist'), ResponseInterface::HTTP_NOT_FOUND); if ($isExist->image != 'public/upload/profile/default-avatar.jpg') { $this->cfs->removeSingleFile(ROOTPATH . $isExist->image); }
if (isset($entity->toArray()['group'])) { $this->groupModel->removeUserFromAllGroups($id); $groupId = $this->groupModel->where('name', $entity->group)->find(); $this->groupModel->addUserToGroup($id, $groupId[0]->id);
}
if (!$this->userModel->update($id, $entity)) {
helper('shared'); $this->httpException(lang('Shared.api.reject'), ResponseInterface::HTTP_BAD_REQUEST, serializeMessages($this->userModel->errors()));
};
}
/** * edit function * @method : DELETE with params ID * @param $id */ public function delete($id) {
$deleteById = $this->userModel->find($id);
if (is_null($deleteById)) $this->httpException(lang('Shared.api.exist'), ResponseInterface::HTTP_NOT_FOUND);
$this->groupModel->removeUserFromAllGroups($id); $this->userModel->delete($id); }
public function getInsertId() { return $this->userModel->getInsertID(); } }
without Aggregation class and urlQueryParam class it always get same data (all data in tables) but if you need only id why we ask for all data in table okay can you see a point ?1
with two this classes we can get data we needs
how back end get such request here s exmpel of using via angular 12
see codes
Code: export interface IQuery {
page?: number;
limit?: number;
offset?: number;
sort?: string;
order?: string;
range?: string;
filed?: string;
embody?: string;
q?: HttpParams;
foreignKey?: number;
}
PHP Code: export interface ISearch { sgn?: string | string[] | null | undefined; val: number | string | string[] | number[] | undefined; fun: string | undefined; jin?: string | null | undefined;
}
Code: export enum FunctionSearchType {
Where = 'where',
OrWhere = 'orWhere',
Like = 'like',
OrLike = 'orLike',
WhereIn = 'whereIn',
WhereNotIn = 'whereNotIn',
OrWhereIn = 'orWhereIn',
OrWhereNotIn = 'orWhereNotIn',
}
in this example search for id and usename
PHP Code: const search: ISearch = { fun: FunctionSearchType.Where, sgn: '', val: this.formGroup.value._key };
let queryParam = new HttpParams(); if (this.sortValue != null) { queryParam = queryParam.append('id', JSON.stringify(search)); } const params: IQuery = { field:'id,username', sort: this.sortValue, order: this.orderValue, q: queryParam };
this.groupService.setQueryArgument(params);
this.router.navigate(['./admin/group/list'], { queryParams: params,
});
}
in this example search like for item
Code: onChangeDataTable(): void {
const search: ISearch = {
fun: FunctionSearchType.Like,
sgn: '',
val: this.formGroup.value._key
};
let queryParam = new HttpParams();
if (this.sortValue != null) {
queryParam = queryParam.append(this.sortValue, JSON.stringify(search));
}
const params: IQuery = {
sort: this.sortValue,
order: this.orderValue,
q: queryParam
};
this.groupService.setQueryArgument(params);
this.router.navigate(['./admin/group/list'], {
queryParams: params,
});
}
its set query for q=id=%257B%2522fun%2522:%2522whr%2522,%2522sgn%2522:%2522=%2522,%2522val%2522:%25222%2522%257D
like that s
$page =1
$['id']=[
'sgn'=>'='
'fun'=>'where',
'val'=>'2'
]
to select filed we want
select=id,name,username & page=1 &q=id=%257B%2522fun%2522:%2522whr%2522,%2522sgn%2522:%2522=%2522,%2522val%2522:%25222%2522%257D
$select="id,name,username"
$page =1
$q['id']=[
'sgn'=>'='
'fun'=>'where',
'val'=>'2'
]
more example
PHP Code: <?php
namespace Modules\Common\Controllers;
use Modules\Common\Config\Services; use Modules\Common\Entities\ViewsOptionEntity; use CodeIgniter\HTTP\ResponseInterface; use Modules\Shared\Controllers\ApiController;
class ViewOption extends ApiController {
/** * index function * @method : GET */ public function index() {
$viewsOptionEntity = new ViewsOptionEntity(); $this->urlQueryParam->dataMap($viewsOptionEntity->getDataMap());
$viewOptionService = Services::viewOptionService(); $findAllData = $viewOptionService->index($this->urlQueryParam);
return $this->respond([ 'data' => $findAllData['data'], 'pager' => $findAllData['pager'] ], ResponseInterface::HTTP_OK, lang('Shared.api.receive'));
}
/** * show function * @method : GET with params ID */ public function show($id = null) {
$viewOptionService = Services::viewOptionService(); $findOneData = $viewOptionService->show($id);
return $this->respond([ 'data' => $findOneData['data'], 'pager' => $findOneData['pager'] ], ResponseInterface::HTTP_OK, lang('Shared.api.receive'));
}
/** * create function * @method : POST */ public function create() {
$rules = [ 'name' => 'required|max_length[255]',
];
if (!$this->validate($rules)) {
return $this->respond([ 'error' => $this->validator->getErrors(), ], ResponseInterface::HTTP_NOT_ACCEPTABLE, lang('Shared.api.validation'));
}
$viewsOptionEntity = new ViewsOptionEntity((array)$this->request->getVar()); $viewOptionService = Services::viewOptionService(); $viewOptionService->create($viewsOptionEntity);
return $this->respond([
], ResponseInterface::HTTP_CREATED, lang('Shared.api.save'));
}
/** * update function * @method : PUT or PATCH */ public function update($id = null) {
//get request from Vue Js $json = $this->request->getJSON(); if (!isset($id)) { $id = $json->id; }
$rules = [ 'name' => 'required|max_length[255]', ];
if (!$this->validate($rules)) {
return $this->respond([ 'error' => $this->validator->getErrors(),
], ResponseInterface::HTTP_NOT_ACCEPTABLE, lang('Shared.api.validation'));
}
$viewsOptionEntity = new ViewsOptionEntity((array)$this->request->getVar());
$viewOptionService = Services::viewOptionService(); $viewOptionService->update($id, $viewsOptionEntity);
return $this->respond([
], ResponseInterface::HTTP_OK, lang('Shared.api.update'));
}
/** * edit function * @method : DELETE with params ID */ public function delete($id = null) {
$viewOptionService = Services::viewOptionService(); $viewOptionService->delete($id); return $this->respond([ ], ResponseInterface::HTTP_OK, lang('Shared.api.remove'));
} }
PHP Code: <?php
namespace Modules\Common\Services;
use Modules\Common\Entities\ViewsOptionEntity; use Modules\Common\Models\ViewOptionModel; use CodeIgniter\HTTP\ResponseInterface; use Modules\Shared\Interfaces\UrlQueryParamInterface; use Modules\Shared\Libraries\MainService;
class ViewOptionService extends MainService { private ViewOptionModel $model;
public function __construct() { $this->model = new ViewOptionModel(); }
/** * index function * @method : GET * @param UrlQueryParamInterface $urlQueryParam * @return array */ public function index(UrlQueryParamInterface $urlQueryParam) { $pipeLine = $urlQueryParam->decodeQueryParam()->getPipeLine();
return $this->model->aggregatePagination($pipeLine);
}
/** * show function * @method : GET with params ID * @param $id * @return array */ public function show($id) { if (is_null($id)) $this->httpException(lang('Shared.api.validation'), ResponseInterface::HTTP_NOT_FOUND);
$result = $this->model->where('id', $id)->paginate(1, 'default');
if (is_null($result)) $this->httpException(lang('Shared.api.exist'), ResponseInterface::HTTP_NOT_FOUND);
$data = [ 'data' => $result, 'pager' => $this->model->pager->getDetails() ]; return $data;
}
/** * create function * @method : POST * @param ViewsOptionEntity $entity * @throws \ReflectionException */ public function create(ViewsOptionEntity $entity) { if (is_null($entity)) $this->httpException(lang('Shared.api.validation'), ResponseInterface::HTTP_NOT_FOUND);
if (!$this->model->save($entity)) { helper('shared'); $this->httpException(lang('Shared.api.reject'), ResponseInterface::HTTP_BAD_REQUEST, serializeMessages($this->model->errors()));
}
}
/** * update function * @method : PUT or PATCH * @param $id * @param ViewsOptionEntity $entity * @throws \ReflectionException */ public function update($id, ViewsOptionEntity $entity) { if (is_null($entity)) $this->httpException(lang('Shared.api.validation'), ResponseInterface::HTTP_NOT_FOUND);
if (!$this->model->update($id, $entity)) {
helper('shared'); $this->httpException(lang('Shared.api.reject'), ResponseInterface::HTTP_BAD_REQUEST, serializeMessages($this->model->errors()));
}
}
/** * edit function * @method : DELETE with params ID * @param $id */ public function delete($id) {
$deleteById = $this->model->find($id);
if (is_null($deleteById)) $this->httpException(lang('Shared.api.exist'), ResponseInterface::HTTP_NOT_FOUND);
$this->model->delete($id);
}
public function getInsertId() { return $this->model->getInsertID(); } }
Enlightenment Is Freedom
|