dbms_init_base

This commit is contained in:
최준흠 2025-05-01 19:06:16 +09:00
parent 1a879d779c
commit 09a0e81247
15 changed files with 195 additions and 145 deletions

View File

@ -5,24 +5,23 @@ namespace App\Controllers\Admin;
use CodeIgniter\HTTP\RequestInterface; use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface; use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
use App\Helpers\CommonHelper as Helper;
use App\Services\UserService as Service; use App\Services\UserService as Service;
class Home extends AdminController class Home extends AdminController
{ {
private $_service = null;
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger) public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
{ {
parent::initController($request, $response, $logger); parent::initController($request, $response, $logger);
$this->title = "관리자페이지 메인"; $this->title = "관리자페이지 메인";
$this->helper = new Helper($this->request);
} }
protected function getServiceClass(): Service
final public function getService(): Service
{ {
if (!$this->service) { if (!$this->_service) {
$this->service = new Service($this->request); $this->_service = new Service($this->request);
} }
return $this->service; return $this->_service;
} }
//Index,FieldForm관련 //Index,FieldForm관련

View File

@ -18,14 +18,14 @@ class MyLogController extends AdminController
parent::initController($request, $response, $logger); parent::initController($request, $response, $logger);
$this->uri_path .= strtolower($this->getService()->getClassName()) . DIRECTORY_SEPARATOR; $this->uri_path .= strtolower($this->getService()->getClassName()) . DIRECTORY_SEPARATOR;
$this->title = lang("MyLog.title"); $this->title = lang("MyLog.title");
$this->helper = new Helper($this->request); $this->helper = new Helper($this->getService());
} }
protected function getServiceClass(): Service final public function getService(): Service
{ {
if (!$this->service) { if (!$this->_service) {
$this->service = new Service(); $this->_service = new Service($this->request);
} }
return $this->service; return $this->_service;
} }
public function getUserService(): UserService public function getUserService(): UserService
{ {

View File

@ -2,8 +2,6 @@
namespace App\Controllers\Admin; namespace App\Controllers\Admin;
use App\Helpers\UserHelper as Helper;
use App\Services\UserService as Service;
use CodeIgniter\HTTP\RedirectResponse; use CodeIgniter\HTTP\RedirectResponse;
use CodeIgniter\HTTP\RequestInterface; use CodeIgniter\HTTP\RequestInterface;
@ -11,6 +9,9 @@ use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Validation\Validation; use CodeIgniter\Validation\Validation;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
use App\Helpers\UserHelper as Helper;
use App\Services\UserService as Service;
class UserController extends AdminController class UserController extends AdminController
{ {
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger) public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
@ -20,12 +21,12 @@ class UserController extends AdminController
$this->title = lang("{$this->getService()->getClassPath()}.title"); $this->title = lang("{$this->getService()->getClassPath()}.title");
$this->helper = new Helper($this->getService()); $this->helper = new Helper($this->getService());
} }
protected function getServiceClass(): Service final public function getService(): Service
{ {
if (!$this->service) { if (!$this->_service) {
$this->service = new Service($this->request); $this->_service = new Service($this->request);
} }
return $this->service; return $this->_service;
} }
//Index,FieldForm관련 //Index,FieldForm관련
public function getFields(): array public function getFields(): array

View File

@ -3,25 +3,27 @@
namespace App\Controllers; namespace App\Controllers;
use App\Controllers\BaseController; use App\Controllers\BaseController;
use App\Libraries\LogCollector;
use App\Services\MyLogService; use App\Services\MyLogService;
use CodeIgniter\HTTP\DownloadResponse; use CodeIgniter\HTTP\DownloadResponse;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\RedirectResponse; use CodeIgniter\HTTP\RedirectResponse;
use CodeIgniter\HTTP\RequestInterface; use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface; use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Validation\Validation; use CodeIgniter\Validation\Validation;
use PDOException;
use PhpOffice\PhpSpreadsheet\IOFactory; use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Reader\Html; use PhpOffice\PhpSpreadsheet\Reader\Html;
use PhpOffice\PhpSpreadsheet\Writer\Pdf\Mpdf; use PhpOffice\PhpSpreadsheet\Writer\Pdf\Mpdf;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
abstract class CommonController extends BaseController abstract class CommonController extends BaseController
{ {
private $_service = null; private $_myLogService = null;
private $_viewDatas = []; private $_viewDatas = [];
abstract protected function getServiceClass(): mixed; abstract public function getService(): mixed;
abstract public function getFields(): array; abstract public function getFields(): array;
abstract public function getFilterFields(): array; abstract public function getFilterFields(): array;
abstract public function getBatchJobFields(): array; abstract public function getBatchJobFields(): array;
@ -41,14 +43,12 @@ abstract class CommonController extends BaseController
{ {
$this->_viewDatas[$name] = $value; $this->_viewDatas[$name] = $value;
} }
final public function getService(): mixed final public function getMyLogService(): mixed
{ {
if (!$this->_service) { if (!$this->_myLogService) {
$serviceClass = $this->getServiceClass(); $this->_myLogService = new MyLogService($this->request);
$this->_service = new $serviceClass($this->request);
// $this->_service->setDebug(true);
} }
return $this->_service; return $this->_myLogService;
} }
protected function getResultPageByActon(string $action, string $message = MESSAGES["SUCCESS"]): RedirectResponse|string protected function getResultPageByActon(string $action, string $message = MESSAGES["SUCCESS"]): RedirectResponse|string
{ {
@ -123,7 +123,7 @@ abstract class CommonController extends BaseController
//Index,FieldForm관련 //Index,FieldForm관련
//Field관련 //Field관련
protected function init(string $action, array $fields = []): void final protected function init(string $action, array $fields = []): void
{ {
$this->action = $action; $this->action = $action;
$this->fields = array_key_exists('fields', $fields) && is_array($fields['fields']) && count($fields['fields']) ? $fields['fields'] : $this->getFields(); $this->fields = array_key_exists('fields', $fields) && is_array($fields['fields']) && count($fields['fields']) ? $fields['fields'] : $this->getFields();
@ -140,7 +140,7 @@ abstract class CommonController extends BaseController
// var_dump($this->field_rules); // var_dump($this->field_rules);
// exit; // exit;
foreach ($fields as $field) { foreach ($fields as $field) {
$validation = $this->setValidation($validation, $this->action, $field, $this->field_rules[$field] ?? null); $validation = $this->setValidation($validation, $action, $field, $this->field_rules[$field] ?? null);
} }
if (!$validation->withRequest($this->request)->run()) { if (!$validation->withRequest($this->request)->run()) {
throw new \Exception("{$this->getService()->getClassName()} 작업 데이터 검증 오류발생\n" . implode( throw new \Exception("{$this->getService()->getClassName()} 작업 데이터 검증 오류발생\n" . implode(
@ -153,7 +153,7 @@ abstract class CommonController extends BaseController
// 생성 // 생성
protected function create_form_process(): void {} protected function create_form_process(): void {}
public function create_form(): RedirectResponse|string final public function create_form(): RedirectResponse|string
{ {
try { try {
$this->init(__FUNCTION__); $this->init(__FUNCTION__);
@ -171,19 +171,19 @@ abstract class CommonController extends BaseController
$this->formDatas = $this->doValidate($this->action, $this->fields); $this->formDatas = $this->doValidate($this->action, $this->fields);
return $this->getService()->create($this->formDatas); return $this->getService()->create($this->formDatas);
} }
public function create(): RedirectResponse|string final public function create(): RedirectResponse|string
{ {
//Transaction Start
$this->getService()->getModel()->transStart(); $this->getService()->getModel()->transStart();
try { try {
$this->init(__FUNCTION__); $this->init(__FUNCTION__);
helper(['form']); helper(['form']);
$this->entity = $this->create_process(); $this->entity = $this->create_process();
$this->getService()->getModel()->transCommit(); $this->getService()->getModel()->transCommit();
$this->getMyLogService()->save($this->getService(), __FUNCTION__, $this->myauth, MESSAGES["SUCCESS"]);
return $this->getResultPageByActon($this->action); return $this->getResultPageByActon($this->action);
} catch (\Exception $e) { } catch (\Exception $e) {
//Transaction Rollback
$this->getService()->getModel()->transRollback(); $this->getService()->getModel()->transRollback();
$this->getMyLogService()->save($this->getService(), __FUNCTION__, $this->myauth, MESSAGES["FAILED"]);
return redirect()->back()->withInput()->with('error', $e->getMessage()); return redirect()->back()->withInput()->with('error', $e->getMessage());
} }
} }
@ -198,7 +198,7 @@ abstract class CommonController extends BaseController
} }
return $entity; return $entity;
} }
public function modify_form(mixed $uid): RedirectResponse|string final public function modify_form(mixed $uid): RedirectResponse|string
{ {
try { try {
$this->init(__FUNCTION__); $this->init(__FUNCTION__);
@ -222,7 +222,7 @@ abstract class CommonController extends BaseController
} }
return $this->getService()->modify($entity, $this->formDatas); return $this->getService()->modify($entity, $this->formDatas);
} }
public function modify(int $uid): RedirectResponse|string final public function modify(int $uid): RedirectResponse|string
{ {
//Transaction Start //Transaction Start
$this->getService()->getModel()->transStart(); $this->getService()->getModel()->transStart();
@ -231,10 +231,11 @@ abstract class CommonController extends BaseController
helper(['form']); helper(['form']);
$this->entity = $this->modify_process($uid); $this->entity = $this->modify_process($uid);
$this->getService()->getModel()->transCommit(); $this->getService()->getModel()->transCommit();
$this->getMyLogService()->save($this->getService(), __FUNCTION__, $this->myauth, MESSAGES["SUCCESS"]);
return $this->getResultPageByActon($this->action); return $this->getResultPageByActon($this->action);
} catch (\Exception $e) { } catch (\Exception $e) {
//Transaction Rollback
$this->getService()->getModel()->transRollback(); $this->getService()->getModel()->transRollback();
$this->getMyLogService()->save($this->getService(), __FUNCTION__, $this->myauth, MESSAGES["FAILED"]);
return redirect()->back()->withInput()->with('error', $e->getMessage()); return redirect()->back()->withInput()->with('error', $e->getMessage());
} }
} }
@ -260,17 +261,21 @@ abstract class CommonController extends BaseController
$this->fields = [$field]; $this->fields = [$field];
$this->entity = $this->toggle_process($uid); $this->entity = $this->toggle_process($uid);
$this->getService()->getModel()->transCommit(); $this->getService()->getModel()->transCommit();
$this->getMyLogService()->save($this->getService(), __FUNCTION__, $this->myauth, MESSAGES["SUCCESS"]);
return $this->getResultPageByActon($this->action); return $this->getResultPageByActon($this->action);
} catch (\Exception $e) { } catch (\Exception $e) {
$this->getService()->getModel()->transRollback(); $this->getService()->getModel()->transRollback();
$this->getMyLogService()->save($this->getService(), __FUNCTION__, $this->myauth, MESSAGES["FAILED"]);
return redirect()->back()->withInput()->with('error', $e->getMessage()); return redirect()->back()->withInput()->with('error', $e->getMessage());
} }
} }
//일괄처리작업 //일괄처리작업
protected function batchjob_process(string $uids): array protected function batchjob_process(array $uids): array
{ {
//데이터 검증
$this->formDatas = $this->doValidate($this->action, $this->fields);
$temps = []; $temps = [];
foreach (explode(",", $uids) as $uid) { foreach ($uids as $uid) {
$entity = $this->getService()->getEntity(); $entity = $this->getService()->getEntity();
if (!$entity) { if (!$entity) {
throw new \Exception("{$uid} 정보를 찾을수 없습니다."); throw new \Exception("{$uid} 정보를 찾을수 없습니다.");
@ -298,30 +303,31 @@ abstract class CommonController extends BaseController
$fields = []; $fields = [];
foreach ($this->batchjob_fields as $field) { foreach ($this->batchjob_fields as $field) {
if ($this->request->getVar($field)) { if ($this->request->getVar($field)) {
$fields[$field] = $field; $fields[] = $field;
} }
} }
//데이터 검증 $this->fields = $fields;
$this->formDatas = $this->doValidate($this->action, $fields); $this->entities = $this->batchjob_process(explode(",", $uids));
$this->entities = $this->batchjob_process($uids); $this->getService()->getModel()->transCommit();
$this->getMyLogService()->save($this->getService(), __FUNCTION__, $this->myauth, MESSAGES["SUCCESS"]);
return $this->getResultPageByActon($this->action); return $this->getResultPageByActon($this->action);
} catch (\Exception $e) { } catch (\Exception $e) {
//Transaction Rollback
$this->getService()->getModel()->transRollback(); $this->getService()->getModel()->transRollback();
$this->getMyLogService()->save($this->getService(), __FUNCTION__, $this->myauth, MESSAGES["FAILED"]);
return redirect()->back()->withInput()->with('error', $e->getMessage()); return redirect()->back()->withInput()->with('error', $e->getMessage());
} }
} }
//삭제,일괄삭제 공통사용 //삭제,일괄삭제 공통사용
protected function delete_process(mixed $entity): bool protected function delete_process(mixed $entity): mixed
{ {
$result = $this->getService()->delete($entity); $result = $this->getService()->delete($entity);
if (!$result) { if (!$result) {
throw new \Exception("[$entity->getTitle()] 삭제를 실패하였습니다."); throw new \Exception("[{$entity->getTitle()}] 삭제실패");
} }
return $result; return $entity;
} }
public function delete(mixed $uid): RedirectResponse|string final public function delete(mixed $uid): RedirectResponse|string
{ {
//Transaction Start //Transaction Start
$this->getService()->getModel()->transStart(); $this->getService()->getModel()->transStart();
@ -334,18 +340,19 @@ abstract class CommonController extends BaseController
} }
$this->entity = $this->delete_process($entity); $this->entity = $this->delete_process($entity);
$this->getService()->getModel()->transCommit(); $this->getService()->getModel()->transCommit();
$this->getMyLogService()->save($this->getService(), __FUNCTION__, $this->myauth, MESSAGES["SUCCESS"]);
return $this->getResultPageByActon($this->action); return $this->getResultPageByActon($this->action);
} catch (\Exception $e) { } catch (\Exception $e) {
//Transaction Rollback
$this->getService()->getModel()->transRollback(); $this->getService()->getModel()->transRollback();
$this->getMyLogService()->save($this->getService(), __FUNCTION__, $this->myauth, MESSAGES["FAILED"]);
return redirect()->back()->withInput()->with('error', $e->getMessage()); return redirect()->back()->withInput()->with('error', $e->getMessage());
} }
} }
//일괄삭제 //일괄삭제
protected function batchjob_delete_process(string $uids): void protected function batchjob_delete_process(array $uids): void
{ {
$entities = []; $entities = [];
foreach (explode(",", $uids) as $uid) { foreach ($uids as $uid) {
$this->getService()->getModel()->where($this->getService()->getModel()::PK, $uid); $this->getService()->getModel()->where($this->getService()->getModel()::PK, $uid);
$entity = $this->getService()->getEntity(); $entity = $this->getService()->getEntity();
if (!$entity) { if (!$entity) {
@ -353,15 +360,17 @@ abstract class CommonController extends BaseController
} }
$entities[] = $entity; $entities[] = $entity;
} }
$fail_cnt = 0;
foreach ($entities as $entity) { foreach ($entities as $entity) {
try { $result = $this->getService()->delete($entity);
if ($this->getService()->delete($entity)) { if (!$result) {
MyLogService::debug("[{$entity->getTitle()}]" . MESSAGES["DELETED"]); LogCollector::error("[{$entity->getTitle()}] 삭제실패");
} $fail_cnt++;
} catch (PDOException $e) {
MyLogService::debug("[{$entity->getTitle()}]" . MESSAGES["FAILED"] . ":" . $e->getMessage());
} }
} }
if ($fail_cnt) {
throw new \Exception("총:" . count($entities) . "중에 " . $fail_cnt . "개를 실패");
}
} }
final public function batchjob_delete(): RedirectResponse|string final public function batchjob_delete(): RedirectResponse|string
{ {
@ -374,14 +383,13 @@ abstract class CommonController extends BaseController
if (!$uids) { if (!$uids) {
throw new \Exception("적용할 리스트를 선택하셔야합니다."); throw new \Exception("적용할 리스트를 선택하셔야합니다.");
} }
$this->batchjob_delete_process($uids); $this->batchjob_delete_process(explode(",", $uids));
MyLogService::save($this->getService(), __FUNCTION__, $this->myauth, MESSAGES["SUCCESS"]);
$this->getService()->getModel()->transCommit(); $this->getService()->getModel()->transCommit();
$this->getMyLogService()->save($this->getService(), __FUNCTION__, $this->myauth, MESSAGES["SUCCESS"]);
return $this->getResultPageByActon($this->action); return $this->getResultPageByActon($this->action);
} catch (\Exception $e) { } catch (\Exception $e) {
//Transaction Rollback
$this->getService()->getModel()->transRollback(); $this->getService()->getModel()->transRollback();
MyLogService::save($this->getService(), __FUNCTION__, $this->myauth, MESSAGES["FAILED"]); $this->getMyLogService()->save($this->getService(), __FUNCTION__, $this->myauth, MESSAGES["FAILED"]);
return redirect()->back()->withInput()->with('error', $e->getMessage()); return redirect()->back()->withInput()->with('error', $e->getMessage());
} }
} }
@ -397,7 +405,7 @@ abstract class CommonController extends BaseController
} }
return $entity; return $entity;
} }
public function view(string $uid): RedirectResponse|string final public function view(string $uid): RedirectResponse|string
{ {
try { try {
$this->init(__FUNCTION__); $this->init(__FUNCTION__);
@ -464,8 +472,6 @@ abstract class CommonController extends BaseController
$this->setConditionForList($this->filter_fields); $this->setConditionForList($this->filter_fields);
//TotalCount //TotalCount
$this->total_count = intval($this->getService()->getModel()->selectCount('*', 'cnt')->get()->getRow()->cnt); $this->total_count = intval($this->getService()->getModel()->selectCount('*', 'cnt')->get()->getRow()->cnt);
// echo $this->total_count;
// exit;
//Pagination 처리 //Pagination 처리
$this->pagination = $this->getPaginationForList(); $this->pagination = $this->getPaginationForList();
//OrderBy 처리 //OrderBy 처리
@ -495,7 +501,7 @@ abstract class CommonController extends BaseController
} }
//OUPUT Document 관련 //OUPUT Document 관련
private function download_process_save(string $document_type, mixed $loaded_data): array private function download_document(string $document_type, mixed $loaded_data): array
{ {
$full_path = WRITEPATH . DIRECTORY_SEPARATOR . "excel"; $full_path = WRITEPATH . DIRECTORY_SEPARATOR . "excel";
switch ($document_type) { switch ($document_type) {
@ -509,25 +515,13 @@ abstract class CommonController extends BaseController
$writer = new Mpdf($loaded_data); $writer = new Mpdf($loaded_data);
$writer->save($full_path . DIRECTORY_SEPARATOR . $file_name); $writer->save($full_path . DIRECTORY_SEPARATOR . $file_name);
break; break;
default:
if (!is_file($full_path)) {
throw new \Exception("첨부파일이 확인되지 않습니다.\n");
}
// //oupuput directly
// header("Content-Type: application/vnd.ms-excel");
// header(sprintf("Content-Disposition: attachment; filename=%s", urlencode($output_name)));
// header("Expires: 0");
// header("Cache-Control: must-revalidate");
// header("Pragma: public");
// header("Content-Length:" . filesize($full_path));
// return $writer->save('php://output');
break;
} }
return array($full_path, $file_name); return array($full_path, $file_name);
} }
//File Download관련 // Download
protected function download_process(string $output_type, mixed $uid = false): DownloadResponse|RedirectResponse final public function download(string $output_type, mixed $uid = false): DownloadResponse|RedirectResponse
{ {
$this->init(__FUNCTION__);
try { try {
helper(['form']); helper(['form']);
//URL처리 //URL처리
@ -541,7 +535,7 @@ abstract class CommonController extends BaseController
//data loading //data loading
$reader = new Html(); $reader = new Html();
$loaded_data = $reader->loadFromString($html); $loaded_data = $reader->loadFromString($html);
list($full_path, $file_name) = $this->download_process_save($output_type, $loaded_data); list($full_path, $file_name) = $this->download_document($output_type, $loaded_data);
$full_path .= DIRECTORY_SEPARATOR . $file_name; $full_path .= DIRECTORY_SEPARATOR . $file_name;
break; break;
default: default:
@ -562,10 +556,4 @@ abstract class CommonController extends BaseController
return redirect()->back()->withInput()->with('error', $e->getMessage()); return redirect()->back()->withInput()->with('error', $e->getMessage());
} }
} }
// Download
final public function download(string $output_type, mixed $uid = false): DownloadResponse|string
{
$this->init(__FUNCTION__);
return $this->download_process($output_type, $uid);
}
} }

View File

@ -3,33 +3,34 @@
namespace App\Controllers; namespace App\Controllers;
use App\Helpers\UserHelper as Helper;
use App\Libraries\MySocket\GoogleSocket\API as GoogleSocket;
use App\Services\Auth\GoogleService;
use App\Services\Auth\LocalService;
use App\Services\UserService as Service;
use CodeIgniter\HTTP\RedirectResponse; use CodeIgniter\HTTP\RedirectResponse;
use CodeIgniter\HTTP\RequestInterface; use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface; use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
use App\Services\UserService as Service;
use App\Helpers\UserHelper as Helper;
use App\Services\Auth\LocalService;
use App\Services\Auth\GoogleService;
use App\Libraries\MySocket\GoogleSocket\API as GoogleSocket;
class UserController extends CommonController class UserController extends CommonController
{ {
private $_service = null;
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger) public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
{ {
parent::initController($request, $response, $logger); parent::initController($request, $response, $logger);
$this->uri_path .= strtolower($this->getService()->getClassName()) . DIRECTORY_SEPARATOR; $this->uri_path .= strtolower($this->getService()->getClassName()) . DIRECTORY_SEPARATOR;
$this->view_path = $this->uri_path; $this->view_path = $this->uri_path;
$this->title = lang("{$this->getService()->getClassPath()}.title");; $this->title = lang("{$this->getService()->getClassPath()}.title");;
$this->helper = new Helper($this->request); $this->helper = new Helper($this->getService());
} }
protected function getServiceClass(): Service final public function getService(): Service
{ {
if (!$this->service) { if (!$this->_service) {
$this->service = new Service($this->request); $this->_service = new Service($this->request);
} }
return $this->service; return $this->_service;
} }
//Index,FieldForm관련 //Index,FieldForm관련
public function getFields(): array public function getFields(): array

View File

@ -16,23 +16,24 @@ abstract class CommonEntity extends Entity
{ {
parent::__construct($data); parent::__construct($data);
} }
final public function getPK(): string final public function getPK(): string
{ {
$field = constant("static::PK"); $field = constant("static::PK");
return $this->$field; return $this->attributes[$field];
} }
final public function getTitle(): string final public function getTitle(): string
{ {
$field = constant("static::TITLE"); $field = constant("static::TITLE");
return $this->$field; return $this->attributes[$field];
} }
final public function getUpdatedAt(): string final public function getUpdatedAt(): string
{ {
return $this->updated_at; return $this->attributes['updated_at'];
} }
final public function getCreatedAt(): string final public function getCreatedAt(): string
{ {
return $this->created_at; return $this->attributes['created_at'];
} }
//공통부분 //공통부분
} }

View File

@ -9,6 +9,7 @@ class MyLogEntity extends CommonEntity
{ {
const PK = Model::PK; const PK = Model::PK;
const TITLE = Model::TITLE; const TITLE = Model::TITLE;
//공통부분 //공통부분
//Common Function //Common Function
} }

View File

@ -9,6 +9,7 @@ class UserEntity extends CommonEntity
{ {
const PK = Model::PK; const PK = Model::PK;
const TITLE = Model::TITLE; const TITLE = Model::TITLE;
public function getID(): string public function getID(): string
{ {
return $this->attributes['id']; return $this->attributes['id'];

View File

@ -9,6 +9,7 @@ class UserSNSEntity extends CommonEntity
{ {
const PK = Model::PK; const PK = Model::PK;
const TITLE = Model::TITLE; const TITLE = Model::TITLE;
//Common Function //Common Function
public function getParent(): int|null public function getParent(): int|null
{ {

View File

@ -10,7 +10,7 @@ class CommonHelper
$this->_service = $service; $this->_service = $service;
} }
final protected function getService() final protected function getService(): mixed
{ {
return $this->_service; return $this->_service;
} }

View File

@ -0,0 +1,39 @@
<?php
namespace App\Libraries;
class LogCollector
{
private static array $_logBuffers = [];
static public function log(string $message, string $level = "info"): void
{
self::$_logBuffers[] = sprintf("%s[%s]: %s", date("H:i:s"), $level, $message);
log_message($level, $message);
}
static public function info(string $message): void
{
self::log($message, 'info');
}
static public function error(string $message): void
{
self::log($message, 'error');
}
static public function warning(string $message): void
{
self::log($message, 'warning');
}
static public function debug(string $message): void
{
self::log($message, 'debug');
}
static public function dump(): string
{
return implode("\n", self::$_logBuffers);
}
public static function clear(): void
{
self::$_logBuffers = [];
}
}

View File

@ -3,6 +3,7 @@
namespace App\Models; namespace App\Models;
use CodeIgniter\Model; use CodeIgniter\Model;
use App\Libraries\LogCollector;
abstract class CommonModel extends Model abstract class CommonModel extends Model
{ {
@ -142,21 +143,20 @@ abstract class CommonModel extends Model
if (!$entity->hasChanged()) { if (!$entity->hasChanged()) {
throw new \Exception(__FUNCTION__ . " 변경된 내용이 없습니다."); throw new \Exception(__FUNCTION__ . " 변경된 내용이 없습니다.");
} }
log_message("debug", var_export($entity, true));
// 최종 저장 시 오류 발생하면 // 최종 저장 시 오류 발생하면
if (!$this->save($entity)) { if (!$this->save($entity)) {
throw new \Exception("저장오류:" . var_export($this->errors(), true)); throw new \Exception(var_export($this->errors(), true));
} }
log_message("debug", $this->getTable() . " => " . __FUNCTION__ . " DB에 {$entity->getTitle()} 저장이 완료되었습니다.");
// log_message("debug", $this->getLastQuery());
return $entity; return $entity;
} catch (\Exception $e) { } catch (\Exception $e) {
throw new \Exception(sprintf( $message = sprintf(
"\n------%s SQL오류-----\n%s\n%s\n------------------------------\n", "\n------%s SQL오류-----\n%s\n%s\n------------------------------\n",
__FUNCTION__, __FUNCTION__,
$this->getLastQuery(), $this->getLastQuery(),
$e->getMessage() $e->getMessage()
)); );
LogCollector::error($message);
throw new \Exception($message);
} }
} }
public function create(array $formDatas, mixed $entity): mixed public function create(array $formDatas, mixed $entity): mixed

View File

@ -3,6 +3,7 @@
namespace App\Services; namespace App\Services;
use CodeIgniter\HTTP\IncomingRequest; use CodeIgniter\HTTP\IncomingRequest;
use App\Libraries\LogCollector;
abstract class CommonService abstract class CommonService
{ {
@ -77,4 +78,33 @@ abstract class CommonService
// dd($options); // dd($options);
return $options; return $options;
} }
public function create(array $formDatas, mixed $entity = null): mixed
{
$entity = $this->getModel()->create($formDatas, $entity);
LogCollector::info("[{$entity->getTitle()}]" . MESSAGES["CREATED"] . ":");
return $entity;
}
public function modify(mixed $entity, array $formDatas): mixed
{
// die(var_export($formDatas, true));
$entity = $this->getModel()->modify($entity, $formDatas);
LogCollector::info("[{$entity->getTitle()}]" . MESSAGES["UPDATED"] . ":");
return $entity;
}
final public function delete(mixed $entity): bool
{
$result = $this->getModel()->delete($entity->getPK());
if (!$result) {
$message = sprintf(
"\n------%s SQL오류-----\n%s\n------------------------------\n",
__FUNCTION__,
$this->getModel()->getLastQuery()
);
LogCollector::error($message);
return false;
}
LogCollector::info("[{$entity->getTitle()}]" . MESSAGES["DELETED"] . ":");
return true;
}
} }

View File

@ -5,54 +5,42 @@ namespace App\Services;
use App\Entities\MyLogEntity as Entity; use App\Entities\MyLogEntity as Entity;
use App\Models\MyLogModel as Model; use App\Models\MyLogModel as Model;
use App\Services\Auth\AuthService; use App\Services\Auth\AuthService;
use CodeIgniter\HTTP\IncomingRequest;
use App\Libraries\LogCollector;
class MyLogService class MyLogService extends CommonService
{ {
private static $_model = null; public function __construct(IncomingRequest $request)
private static $_logBuffers = [];
public function __construct() {}
static public function getModel(): Model
{ {
if (!self::$_model) { parent::__construct($request);
self::$_model = new Model();
}
return self::$_model;
} }
static public function log(string $message, string $level = "info"): void final public function getClassName(): string
{ {
self::$_logBuffers[] = sprintf("%s[%s]: %s", date("H:i:s"), $level, $message); return "MyLog";
log_message($level, $message);
} }
static public function info(string $message): void final public function getClassPath(): string
{ {
self::log($message, 'info'); return $this->getClassName();
} }
static public function error(string $message): void public function getModelClass(): string
{ {
self::log($message, 'error'); return Model::class;
} }
static public function warning(string $message): void public function getEntityClass(): string
{ {
self::log($message, 'warning'); return Entity::class;
} }
static public function debug(string $message): void
{ public function save($service, string $method, AuthService $myauth, string $title): Entity
self::log($message, 'debug');
}
static public function dump()
{
return implode("\n", self::$_logBuffers);
}
static public function save($service, string $method, AuthService $myauth, string $title): Entity
{ {
$formDatas = [ $formDatas = [
'user_uid' => $myauth->getUIDByAuthInfo(), 'user_uid' => $myauth->getUIDByAuthInfo(),
'class_name' => $service->getClassName(), 'class_name' => $service->getClassName(),
'method_name' => $method, 'method_name' => $method,
'title' => $title, 'title' => $title,
'content' => implode("\n", self::$_logBuffers), 'content' => LogCollector::dump(),
]; ];
self::$_logBuffers = []; LogCollector::clear();
return self::getModel()->create($formDatas, new Entity()); return $this->getModel()->create($formDatas, new Entity());
} }
} }

View File

@ -39,12 +39,12 @@ class UserService extends CommonService
} }
return $options; return $options;
} }
public function create(array $formDatas): Entity public function create(array $formDatas, mixed $entity = null): Entity
{ {
$formDatas['role'] = implode(DEFAULTS["DELIMITER_ROLE"], $formDatas['role']); $formDatas['role'] = implode(DEFAULTS["DELIMITER_ROLE"], $formDatas['role']);
return $this->getModel()->create($formDatas, new Entity()); return parent::create($formDatas, $entity ?? new Entity());
} }
public function modify(Entity $entity, array $formDatas): Entity public function modify(mixed $entity, array $formDatas): Entity
{ {
// die(var_export($formDatas, true)); // die(var_export($formDatas, true));
//암호를 입력하지 않았을시는 변경하기 않게 하기위함 //암호를 입력하지 않았을시는 변경하기 않게 하기위함
@ -57,10 +57,10 @@ class UserService extends CommonService
$formDatas['role'] = implode(DEFAULTS["DELIMITER_ROLE"], $formDatas['role']); $formDatas['role'] = implode(DEFAULTS["DELIMITER_ROLE"], $formDatas['role']);
} }
// die(var_export($formDatas, true)); // die(var_export($formDatas, true));
return $this->getModel()->modify($entity, $formDatas); return parent::modify($entity, $formDatas);
} }
public function delete(Entity $entity): bool public function delete(mixed $entity): bool
{ {
return $this->getModel()->delete($entity); return parent::delete($entity);
} }
} }