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

View File

@ -18,14 +18,14 @@ class MyLogController extends AdminController
parent::initController($request, $response, $logger);
$this->uri_path .= strtolower($this->getService()->getClassName()) . DIRECTORY_SEPARATOR;
$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) {
$this->service = new Service();
if (!$this->_service) {
$this->_service = new Service($this->request);
}
return $this->service;
return $this->_service;
}
public function getUserService(): UserService
{

View File

@ -2,8 +2,6 @@
namespace App\Controllers\Admin;
use App\Helpers\UserHelper as Helper;
use App\Services\UserService as Service;
use CodeIgniter\HTTP\RedirectResponse;
use CodeIgniter\HTTP\RequestInterface;
@ -11,6 +9,9 @@ use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Validation\Validation;
use Psr\Log\LoggerInterface;
use App\Helpers\UserHelper as Helper;
use App\Services\UserService as Service;
class UserController extends AdminController
{
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->helper = new Helper($this->getService());
}
protected function getServiceClass(): Service
final public function getService(): Service
{
if (!$this->service) {
$this->service = new Service($this->request);
if (!$this->_service) {
$this->_service = new Service($this->request);
}
return $this->service;
return $this->_service;
}
//Index,FieldForm관련
public function getFields(): array

View File

@ -3,25 +3,27 @@
namespace App\Controllers;
use App\Controllers\BaseController;
use App\Libraries\LogCollector;
use App\Services\MyLogService;
use CodeIgniter\HTTP\DownloadResponse;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\RedirectResponse;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Validation\Validation;
use PDOException;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Reader\Html;
use PhpOffice\PhpSpreadsheet\Writer\Pdf\Mpdf;
use Psr\Log\LoggerInterface;
abstract class CommonController extends BaseController
{
private $_service = null;
private $_myLogService = null;
private $_viewDatas = [];
abstract protected function getServiceClass(): mixed;
abstract public function getService(): mixed;
abstract public function getFields(): array;
abstract public function getFilterFields(): array;
abstract public function getBatchJobFields(): array;
@ -41,14 +43,12 @@ abstract class CommonController extends BaseController
{
$this->_viewDatas[$name] = $value;
}
final public function getService(): mixed
final public function getMyLogService(): mixed
{
if (!$this->_service) {
$serviceClass = $this->getServiceClass();
$this->_service = new $serviceClass($this->request);
// $this->_service->setDebug(true);
if (!$this->_myLogService) {
$this->_myLogService = new MyLogService($this->request);
}
return $this->_service;
return $this->_myLogService;
}
protected function getResultPageByActon(string $action, string $message = MESSAGES["SUCCESS"]): RedirectResponse|string
{
@ -123,7 +123,7 @@ abstract class CommonController extends BaseController
//Index,FieldForm관련
//Field관련
protected function init(string $action, array $fields = []): void
final protected function init(string $action, array $fields = []): void
{
$this->action = $action;
$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);
// exit;
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()) {
throw new \Exception("{$this->getService()->getClassName()} 작업 데이터 검증 오류발생\n" . implode(
@ -153,7 +153,7 @@ abstract class CommonController extends BaseController
// 생성
protected function create_form_process(): void {}
public function create_form(): RedirectResponse|string
final public function create_form(): RedirectResponse|string
{
try {
$this->init(__FUNCTION__);
@ -171,19 +171,19 @@ abstract class CommonController extends BaseController
$this->formDatas = $this->doValidate($this->action, $this->fields);
return $this->getService()->create($this->formDatas);
}
public function create(): RedirectResponse|string
final public function create(): RedirectResponse|string
{
//Transaction Start
$this->getService()->getModel()->transStart();
try {
$this->init(__FUNCTION__);
helper(['form']);
$this->entity = $this->create_process();
$this->getService()->getModel()->transCommit();
$this->getMyLogService()->save($this->getService(), __FUNCTION__, $this->myauth, MESSAGES["SUCCESS"]);
return $this->getResultPageByActon($this->action);
} catch (\Exception $e) {
//Transaction Rollback
$this->getService()->getModel()->transRollback();
$this->getMyLogService()->save($this->getService(), __FUNCTION__, $this->myauth, MESSAGES["FAILED"]);
return redirect()->back()->withInput()->with('error', $e->getMessage());
}
}
@ -198,7 +198,7 @@ abstract class CommonController extends BaseController
}
return $entity;
}
public function modify_form(mixed $uid): RedirectResponse|string
final public function modify_form(mixed $uid): RedirectResponse|string
{
try {
$this->init(__FUNCTION__);
@ -222,7 +222,7 @@ abstract class CommonController extends BaseController
}
return $this->getService()->modify($entity, $this->formDatas);
}
public function modify(int $uid): RedirectResponse|string
final public function modify(int $uid): RedirectResponse|string
{
//Transaction Start
$this->getService()->getModel()->transStart();
@ -231,10 +231,11 @@ abstract class CommonController extends BaseController
helper(['form']);
$this->entity = $this->modify_process($uid);
$this->getService()->getModel()->transCommit();
$this->getMyLogService()->save($this->getService(), __FUNCTION__, $this->myauth, MESSAGES["SUCCESS"]);
return $this->getResultPageByActon($this->action);
} catch (\Exception $e) {
//Transaction Rollback
$this->getService()->getModel()->transRollback();
$this->getMyLogService()->save($this->getService(), __FUNCTION__, $this->myauth, MESSAGES["FAILED"]);
return redirect()->back()->withInput()->with('error', $e->getMessage());
}
}
@ -260,17 +261,21 @@ abstract class CommonController extends BaseController
$this->fields = [$field];
$this->entity = $this->toggle_process($uid);
$this->getService()->getModel()->transCommit();
$this->getMyLogService()->save($this->getService(), __FUNCTION__, $this->myauth, MESSAGES["SUCCESS"]);
return $this->getResultPageByActon($this->action);
} catch (\Exception $e) {
$this->getService()->getModel()->transRollback();
$this->getMyLogService()->save($this->getService(), __FUNCTION__, $this->myauth, MESSAGES["FAILED"]);
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 = [];
foreach (explode(",", $uids) as $uid) {
foreach ($uids as $uid) {
$entity = $this->getService()->getEntity();
if (!$entity) {
throw new \Exception("{$uid} 정보를 찾을수 없습니다.");
@ -298,30 +303,31 @@ abstract class CommonController extends BaseController
$fields = [];
foreach ($this->batchjob_fields as $field) {
if ($this->request->getVar($field)) {
$fields[$field] = $field;
$fields[] = $field;
}
}
//데이터 검증
$this->formDatas = $this->doValidate($this->action, $fields);
$this->entities = $this->batchjob_process($uids);
$this->fields = $fields;
$this->entities = $this->batchjob_process(explode(",", $uids));
$this->getService()->getModel()->transCommit();
$this->getMyLogService()->save($this->getService(), __FUNCTION__, $this->myauth, MESSAGES["SUCCESS"]);
return $this->getResultPageByActon($this->action);
} catch (\Exception $e) {
//Transaction Rollback
$this->getService()->getModel()->transRollback();
$this->getMyLogService()->save($this->getService(), __FUNCTION__, $this->myauth, MESSAGES["FAILED"]);
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);
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
$this->getService()->getModel()->transStart();
@ -334,18 +340,19 @@ abstract class CommonController extends BaseController
}
$this->entity = $this->delete_process($entity);
$this->getService()->getModel()->transCommit();
$this->getMyLogService()->save($this->getService(), __FUNCTION__, $this->myauth, MESSAGES["SUCCESS"]);
return $this->getResultPageByActon($this->action);
} catch (\Exception $e) {
//Transaction Rollback
$this->getService()->getModel()->transRollback();
$this->getMyLogService()->save($this->getService(), __FUNCTION__, $this->myauth, MESSAGES["FAILED"]);
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 = [];
foreach (explode(",", $uids) as $uid) {
foreach ($uids as $uid) {
$this->getService()->getModel()->where($this->getService()->getModel()::PK, $uid);
$entity = $this->getService()->getEntity();
if (!$entity) {
@ -353,14 +360,16 @@ abstract class CommonController extends BaseController
}
$entities[] = $entity;
}
$fail_cnt = 0;
foreach ($entities as $entity) {
try {
if ($this->getService()->delete($entity)) {
MyLogService::debug("[{$entity->getTitle()}]" . MESSAGES["DELETED"]);
$result = $this->getService()->delete($entity);
if (!$result) {
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
@ -374,14 +383,13 @@ abstract class CommonController extends BaseController
if (!$uids) {
throw new \Exception("적용할 리스트를 선택하셔야합니다.");
}
$this->batchjob_delete_process($uids);
MyLogService::save($this->getService(), __FUNCTION__, $this->myauth, MESSAGES["SUCCESS"]);
$this->batchjob_delete_process(explode(",", $uids));
$this->getService()->getModel()->transCommit();
$this->getMyLogService()->save($this->getService(), __FUNCTION__, $this->myauth, MESSAGES["SUCCESS"]);
return $this->getResultPageByActon($this->action);
} catch (\Exception $e) {
//Transaction Rollback
$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());
}
}
@ -397,7 +405,7 @@ abstract class CommonController extends BaseController
}
return $entity;
}
public function view(string $uid): RedirectResponse|string
final public function view(string $uid): RedirectResponse|string
{
try {
$this->init(__FUNCTION__);
@ -464,8 +472,6 @@ abstract class CommonController extends BaseController
$this->setConditionForList($this->filter_fields);
//TotalCount
$this->total_count = intval($this->getService()->getModel()->selectCount('*', 'cnt')->get()->getRow()->cnt);
// echo $this->total_count;
// exit;
//Pagination 처리
$this->pagination = $this->getPaginationForList();
//OrderBy 처리
@ -495,7 +501,7 @@ abstract class CommonController extends BaseController
}
//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";
switch ($document_type) {
@ -509,25 +515,13 @@ abstract class CommonController extends BaseController
$writer = new Mpdf($loaded_data);
$writer->save($full_path . DIRECTORY_SEPARATOR . $file_name);
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);
}
//File Download관련
protected function download_process(string $output_type, mixed $uid = false): DownloadResponse|RedirectResponse
// Download
final public function download(string $output_type, mixed $uid = false): DownloadResponse|RedirectResponse
{
$this->init(__FUNCTION__);
try {
helper(['form']);
//URL처리
@ -541,7 +535,7 @@ abstract class CommonController extends BaseController
//data loading
$reader = new 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;
break;
default:
@ -562,10 +556,4 @@ abstract class CommonController extends BaseController
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;
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\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
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
{
private $_service = null;
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
$this->uri_path .= strtolower($this->getService()->getClassName()) . DIRECTORY_SEPARATOR;
$this->view_path = $this->uri_path;
$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) {
$this->service = new Service($this->request);
if (!$this->_service) {
$this->_service = new Service($this->request);
}
return $this->service;
return $this->_service;
}
//Index,FieldForm관련
public function getFields(): array

View File

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

View File

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

View File

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

View File

@ -10,7 +10,7 @@ class CommonHelper
$this->_service = $service;
}
final protected function getService()
final protected function getService(): mixed
{
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;
use CodeIgniter\Model;
use App\Libraries\LogCollector;
abstract class CommonModel extends Model
{
@ -142,21 +143,20 @@ abstract class CommonModel extends Model
if (!$entity->hasChanged()) {
throw new \Exception(__FUNCTION__ . " 변경된 내용이 없습니다.");
}
log_message("debug", var_export($entity, true));
// 최종 저장 시 오류 발생하면
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;
} catch (\Exception $e) {
throw new \Exception(sprintf(
$message = sprintf(
"\n------%s SQL오류-----\n%s\n%s\n------------------------------\n",
__FUNCTION__,
$this->getLastQuery(),
$e->getMessage()
));
);
LogCollector::error($message);
throw new \Exception($message);
}
}
public function create(array $formDatas, mixed $entity): mixed

View File

@ -3,6 +3,7 @@
namespace App\Services;
use CodeIgniter\HTTP\IncomingRequest;
use App\Libraries\LogCollector;
abstract class CommonService
{
@ -77,4 +78,33 @@ abstract class CommonService
// dd($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\Models\MyLogModel as Model;
use App\Services\Auth\AuthService;
use CodeIgniter\HTTP\IncomingRequest;
use App\Libraries\LogCollector;
class MyLogService
class MyLogService extends CommonService
{
private static $_model = null;
private static $_logBuffers = [];
public function __construct() {}
static public function getModel(): Model
public function __construct(IncomingRequest $request)
{
if (!self::$_model) {
self::$_model = new Model();
parent::__construct($request);
}
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);
log_message($level, $message);
return "MyLog";
}
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
{
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
public function save($service, string $method, AuthService $myauth, string $title): Entity
{
$formDatas = [
'user_uid' => $myauth->getUIDByAuthInfo(),
'class_name' => $service->getClassName(),
'method_name' => $method,
'title' => $title,
'content' => implode("\n", self::$_logBuffers),
'content' => LogCollector::dump(),
];
self::$_logBuffers = [];
return self::getModel()->create($formDatas, new Entity());
LogCollector::clear();
return $this->getModel()->create($formDatas, new Entity());
}
}

View File

@ -39,12 +39,12 @@ class UserService extends CommonService
}
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']);
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));
//암호를 입력하지 않았을시는 변경하기 않게 하기위함
@ -57,10 +57,10 @@ class UserService extends CommonService
$formDatas['role'] = implode(DEFAULTS["DELIMITER_ROLE"], $formDatas['role']);
}
// 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);
}
}