shoppingmallv2 init...

This commit is contained in:
최준흠 2023-08-01 10:58:12 +09:00
parent 8260c76739
commit 1085cd7bdc
29 changed files with 202 additions and 582 deletions

View File

@ -1,157 +0,0 @@
<?php
namespace App\Backend;
use App\Entities\BaseEntity;
use App\Models\UserModel;
abstract class BaseBackend
{
private $_userModel = null;
private $_className = null;
private $_user_uids = array();
protected $_model = null;
protected $_session = null;
protected function __construct(string $className)
{
$this->_className = $className;
$this->_session = \Config\Services::session();
}
//공통사용
final public function getClassName()
{
return $this->_className;
}
//User모델
final public function getUserModel(): UserModel
{
return is_null($this->_userModel) ? new UserModel() : $this->_userModel;
}
//초기 선언부-------
//Title Field
public function getTitleField()
{
return $this->_model->getTitleField();
}
//Form Fields
public function getFields(string $action): array
{
return $this->_model->getFields($action);
}
//Field별 Form Rule용
public function getFieldRules(array $fields, string $action): array
{
return $this->_model->getFieldRules($fields, $action);
}
//Field별 Form Filter용
public function getFieldFilters(): array
{
return $this->_model->getFieldFilters();
}
//Field별 Form BatchFilter용
public function getFieldBatchFilters(): array
{
return $this->_model->getFieldBatchFilters();
}
//Field별 Form Option용
public function getFieldFormOption(string $field): array
{
switch ($field) {
case 'user_uid':
$options = $this->_user_uids = $this->_user_uids ?: $this->getUserModel()->getFieldFormOptions(['status' => 'use']);
break;
default:
$options = lang($this->_className . '.' . strtoupper($field));
break;
}
if (!is_array($options)) {
throw new \Exception(__FUNCTION__ . "에서 {$this->_className}의 Field:{$field}의 FormOptionData가 array가 아닙니다.\n" . var_export($options, true));
}
return $options;
}
//Field별 Form Option용
final public function getFieldFormOptions(array $fields): array
{
$fieldFormOptions = array();
foreach ($fields as $field) {
if (!is_string($field)) {
throw new \Exception(__FUNCTION__ . "에서 {$this->_className}의 Field:{$field}가 string 아닙니다.\n" . var_export($fields, true));
}
$fieldFormOptions[$field] = $this->getFieldFormOption($field);
}
return $fieldFormOptions;
}
//Entity값 가져오기
public function getEntity($uid)
{
return $this->_model->getEntity([$this->_model->getPrimaryKey() => $uid]);
}
public function getEntitys($condition)
{
return $this->_model->getEntitys($condition);
}
//-----초기 선언부
//transaction관련
final public function transStart($isTest = false)
{
$this->_model->transStart($isTest);
}
final public function transComplete()
{
$this->_model->transComplete();
}
final public function transRollback()
{
$this->_model->transRollback();
}
//Insert관련
public function insert(array $fieldDatas): BaseEntity
{
return $this->_model->create($fieldDatas);
}
//Update관련
public function update($entity, array $fieldDatas)
{
return $this->_model->modify($entity, $fieldDatas);
}
//Delete 관련
public function delete($entity)
{
if (!$this->_model->delete($entity->getPrimaryKey())) {
log_message("error", __FUNCTION__ . "에서 호출:" . $this->_model->getLastQuery());
log_message("error", implode("\n", $this->_model->errors()));
throw new \Exception(__FUNCTION__ . " 오류 발생.\n" . var_export($this->_model->errors(), true));
}
}
//View 관련
public function view($entity)
{
return $entity;
}
public function setCondition(array $filterFields, $word, $start, $end, $order_field, $order_value)
{
foreach ($filterFields as $field => $value) {
$this->_model->where($field, $value);
}
if (!is_null($word)) {
$this->_model->setIndexWordFilter($word);
}
if (!is_null($start) && !is_null($end)) {
$this->_model->setIndexDateFilter($start, $end);
}
$this->_model->setIndexOrderBy($order_field, $order_value);
}
final public function getTotalCount()
{
return $this->_model->countAllResults();
}
final public function getFindEntitys(int $page = 0, int $per_page = 0)
{
return $per_page ? $this->_model->findAll($per_page, $page * $per_page - $per_page) : $this->_model->findAll();
}
}

View File

@ -1,21 +0,0 @@
<?php
namespace App\Backend;
abstract class BaseHierarchyBackend extends BaseBackend
{
public function __construct(string $className)
{
parent::__construct($className);
}
//ContentField
final public function getContentField()
{
return $this->_model->getContentField();
}
//Reply관련
public function reply($entity, array $fieldDatas)
{
return $this->_model->reply($entity, $fieldDatas);
}
}

View File

@ -1,78 +0,0 @@
<?php
namespace App\Backend;
use App\Models\BoardConfigModel;
use App\Models\BoardModel;
class BoardBackend extends BaseHierarchyBackend
{
private $_board_config_uids = null;
private $_boardConfigModel = null;
public function __construct()
{
parent::__construct('Board');
$this->_model = new BoardModel();
}
//BoardConfig모델
public function getBoardConfigModel(): BoardConfigModel
{
return is_null($this->_boardConfigModel) ? new BoardConfigModel() : $this->_boardConfigModel;
}
//초기선언부
//Entity값 가져오기
public function getEntity($uid)
{
return $this->_model->getEntity([$this->_model->getPrimaryKey() => $uid]);
}
public function getFields(string $action)
{
return $this->_model->getFields($action);
}
//TitleField
public function getTitleField()
{
return $this->_model->getTitleField();
}
//Field별 Form Rule용
public function getFieldRules(array $fields, string $action)
{
return $this->_model->getFieldRules($fields, $action);
}
//Field별 Form Filter용
public function getFieldFilters()
{
return $this->_model->getFieldFilters();
}
//Field별 Form BatchFilter용
public function getFieldBatchFilters()
{
return $this->_model->getFieldBatchFilters();
}
//Field별 Form Option용
public function getFieldFormOption(string $field): array
{
switch ($field) {
case 'board_config_uid':
$options = $this->_board_config_uids = $this->_board_config_uids ?: $this->getBoardConfigModel()->getFieldFormOptions(['status' => 'use']);
break;
default:
return parent::getFieldFormOption($field);
break;
}
if (!is_array($options)) {
throw new \Exception(__FUNCTION__ . "에서 {$this->getClassName()}의 Field:{$field}의 FormOptionData가 array가 아닙니다.\n" . var_export($options, true));
}
return $options;
}
//View관련
public function view($entity)
{
//view_cnt에 추가하기위함
$this->_model->increaseViewCount($entity->getPrimaryKey());
return parent::view($entity);
}
}

View File

@ -1,14 +0,0 @@
<?php
namespace App\Backend;
use App\Models\BoardConfigModel;
class BoardConfigBackend extends BaseBackend
{
public function __construct()
{
parent::__construct('BoardConfig');
$this->_model = new BoardConfigModel();
}
}

View File

@ -1,14 +0,0 @@
<?php
namespace App\Backend;
use App\Models\CategoryModel;
class CategoryBackend extends BaseHierarchyBackend
{
public function __construct()
{
parent::__construct('Category');
$this->_model = new CategoryModel();
}
}

View File

@ -1,48 +0,0 @@
<?php
namespace App\Backend;
use App\Entities\OrderEntity;
use App\Entities\ProductEntity;
use App\Models\OrderModel;
use App\Models\ProductModel;
class OrderBackend extends BaseBackend
{
private $_productModel = null;
private $_product_uids = array();
public function __construct()
{
parent::__construct('Order');
$this->_model = new OrderModel();
}
//Porduct모델
final public function getProductModel(): ProductModel
{
return is_null($this->_productModel) ? new ProductModel() : $this->_productModel;
}
//Field별 Form Option용
public function getFieldFormOption(string $field): array
{
switch ($field) {
case 'product_uid':
$options = $this->_product_uids = $this->_product_uids ?: $this->getProductModel()->getFieldFormOptions([]);
break;
default:
return parent::getFieldFormOption($field);
break;
}
if (!is_array($options)) {
throw new \Exception(__FUNCTION__ . "에서 {$this->getClassName()}의 Field:{$field}의 FormOptionData가 array가 아닙니다.\n" . var_export($options, true));
}
return $options;
}
//장바구니에 담기 및 Product 재고 차감
public function addCart(ProductEntity $product, int $quantity, int $price): OrderEntity
{
return $this->_model->addCart($product, $quantity, $price);
}
}

View File

@ -1,74 +0,0 @@
<?php
namespace App\Backend;
use App\Entities\ProductEntity;
use App\Models\CategoryModel;
use App\Models\ProductModel;
class ProductBackend extends BaseBackend
{
private $_categoryModel = null;
private $_category_uids = null;
public function __construct()
{
parent::__construct('Product');
$this->_model = new ProductModel();
}
//Category모델
final protected function getCategoryModel(): CategoryModel
{
return is_null($this->_categoryModel) ? new CategoryModel() : $this->_categoryModel;
}
//Field별 Form Option용
public function getFieldFormOption(string $field): array
{
switch ($field) {
case 'category_uid':
$options = $this->_category_uids = $this->_category_uids ?: $this->getCategoryModel()->getFieldFormOptions(['status' => 'use']);
break;
default:
return parent::getFieldFormOption($field);
break;
}
if (!is_array($options)) {
throw new \Exception(__FUNCTION__ . "에서 {$this->getClassName()}의 Field:{$field}의 FormOptionData가 array가 아닙니다.\n" . var_export($options, true));
}
return $options;
}
public function addCart(ProductEntity $product, int $quantity, int $price)
{
if (!$quantity) {
throw new \Exception("제품 구매수량을 확인해주세요");
}
if (!$price) {
throw new \Exception("제품 구매금액을 확인해주세요");
}
if ($product->getStock() < $quantity) {
throw new \Exception(sprintf(
"%s의 재고수[%s]보다 많은 수량[%s]을 주문하셨습니다.\\n",
$product->getTitle(),
$product->getStock(),
$quantity
));
}
//구매금액 = (판매가-할인가)*구매수량과 맞는지 다시 확인.
// $calculated_price = ($product->getPrice() - $product->getSale()) * $quantity;
$calculated_price = ($product->getPrice() - $product->getSale()) * $quantity;
if ($price != $calculated_price) {
throw new \Exception(
sprintf(
"%s상품의 구매금액[%s원]과 판매금액[%s원]이 맞지않습니다.",
$product->getTitle(),
number_format($price),
number_format($calculated_price)
)
);
}
//상품모델에서 Order에 담은 갯수만큼 재고에서 뺀다.
$this->_model->addCart($product, $quantity);
}
}

View File

@ -1,14 +0,0 @@
<?php
namespace App\Backend;
use App\Models\UserModel;
class UserBackend extends BaseBackend
{
public function __construct()
{
parent::__construct('User');
$this->_model = new UserModel();
}
}

View File

@ -1,14 +0,0 @@
<?php
namespace App\Backend;
use App\Models\UserSNSModel;
class UserSNSBackend extends BaseBackend
{
public function __construct()
{
parent::__construct('UserSNS');
$this->_model = new UserSNSModel();
}
}

View File

@ -29,60 +29,12 @@ class Services extends BaseService
* return new \CodeIgniter\Example();
* }
*/
public static function user($getShared = true)
{
if ($getShared) {
return static::getSharedInstance('user');
}
return new \App\Backend\UserBackend();
}
public static function usersns($getShared = true)
{
if ($getShared) {
return static::getSharedInstance('usersns');
}
return new \App\Backend\UserSNSBackend();
}
public static function board($getShared = true)
{
if ($getShared) {
return static::getSharedInstance('board');
}
return new \App\Backend\BoardBackend();
}
public static function boardconfig($getShared = true)
{
if ($getShared) {
return static::getSharedInstance('boardconfig');
}
return new \App\Backend\BoardConfigBackend();
}
public static function category($getShared = true)
{
if ($getShared) {
return static::getSharedInstance('category');
}
return new \App\Backend\CategoryBackend();
}
public static function product($getShared = true)
{
if ($getShared) {
return static::getSharedInstance('product');
}
return new \App\Backend\ProductBackend();
}
public static function order($getShared = true)
{
if ($getShared) {
return static::getSharedInstance('order');
}
return new \App\Backend\OrderBackend();
}
public static function ecommerce($getShared = true)
{
if ($getShared) {
return static::getSharedInstance('ecommerce');
}
return new \App\Backend\EcommerceBackend();
return new \App\Service\EcommerceService();
}
}

View File

@ -2,6 +2,7 @@
namespace App\Controllers\Admin;
use App\Models\BoardConfigModel;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;
@ -10,8 +11,8 @@ class BoardConfigController extends AdminController
{
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
{
$this->_backend = service('boardconfig');
$this->_model = new BoardConfigModel();
parent::initController($request, $response, $logger);
$this->_viewPath .= strtolower($this->_backend->getClassName());
$this->_viewPath .= strtolower($this->_model->getClassName());
}
}

View File

@ -2,6 +2,7 @@
namespace App\Controllers\Admin;
use App\Models\BoardModel;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;
@ -10,9 +11,9 @@ class BoardController extends AdminController
{
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
{
$this->_backend = service('board');
$this->_model = new BoardModel();
parent::initController($request, $response, $logger);
$this->_viewPath .= strtolower($this->_backend->getClassName());
$this->_viewPath .= strtolower($this->_model->getClassName());
}
//Field별 Form Datas 처리용

View File

@ -2,6 +2,7 @@
namespace App\Controllers\Admin;
use App\Models\CategoryModel;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;
@ -10,8 +11,8 @@ class CategoryController extends AdminController
{
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
{
$this->_backend = service('category');
$this->_model = new CategoryModel();
parent::initController($request, $response, $logger);
$this->_viewPath .= strtolower($this->_backend->getClassName());
$this->_viewPath .= strtolower($this->_model->getClassName());
}
}

View File

@ -8,12 +8,12 @@ use Psr\Log\LoggerInterface;
class EcommerceController extends AdminController
{
private $_service = null;
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
{
$this->_backend = service('ecommerce');
$this->_service = service('ecommerce');
parent::initController($request, $response, $logger);
$this->_viewPath .= strtolower($this->_backend->getClassName());
$this->_viewPath .= strtolower($this->_service->getClassName());
}
protected function addCart_process()
@ -33,32 +33,33 @@ class EcommerceController extends AdminController
{
$msg = "";
try {
$this->_viewDatas['fields'] = $this->_backend->getFields(__FUNCTION__);
$this->_viewDatas['fieldRules'] = $this->_backend->getFieldRules($this->_viewDatas['fields'], __FUNCTION__);
$this->_viewDatas['fields'] = $this->_service->getFields(__FUNCTION__);
$this->_viewDatas['fieldRules'] = $this->_service->getFieldRules($this->_viewDatas['fields'], __FUNCTION__);
//Transaction 시작
// $this->_backend->transStart();
$this->_service->transStart();
$this->addCart_process();
$this->_backend->addCart($this->_viewDatas['fieldDatas']);
$this->_service->addCart($this->_viewDatas['fieldDatas']);
//Transaction Commit
// $this->_backend->transCommit();
$this->_service->transCommit();
$msg = sprintf(
"%s에서 해당 상품 %s개를 장바구니에 담았습니다.",
$this->_viewDatas['title'],
$this->_viewDatas['fieldDatas']['quantity']
);
return redirect()->to($this->_session->getFlashdata(SESSION_NAMES['RETURN_URL']));
} catch (\Exception $e) {
//Transaction Rollback
// $this->_backend->transRollback();
$this->_service->transRollback();
log_message("error", $e->getMessage());
log_message("error", var_export($this->_viewDatas['fieldDatas'], true));
$msg = sprintf(
"%s에서 다음 오류로 인해 장바구니에 담기를 실패하였습니다.\n%s",
$this->_viewDatas['title'],
$e->getMessage()
);
log_message("error", $e->getMessage());
log_message("error", var_export($this->_viewDatas['fieldDatas'], true));
return redirect()->to($this->_session->getFlashdata(SESSION_NAMES['RETURN_URL']));
} finally {
$this->_session->setFlashdata("return_message", $msg);
return redirect()->to($this->_session->getFlashdata(SESSION_NAMES['RETURN_URL']));
}
}
}

View File

@ -2,6 +2,7 @@
namespace App\Controllers\Admin;
use App\Models\OrderModel;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;
@ -11,8 +12,8 @@ class OrderController extends AdminController
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
{
$this->_backend = service('order');
$this->_model = new OrderModel();
parent::initController($request, $response, $logger);
$this->_viewPath .= strtolower($this->_backend->getClassName());
$this->_viewPath .= strtolower($this->_model->getClassName());
}
}

View File

@ -2,6 +2,7 @@
namespace App\Controllers\Admin;
use App\Models\ProductModel;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;
@ -11,9 +12,9 @@ class ProductController extends AdminController
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
{
$this->_backend = service('product');
$this->_model = new ProductModel();
parent::initController($request, $response, $logger);
$this->_viewPath .= strtolower($this->_backend->getClassName());
$this->_viewPath .= strtolower($this->_model->getClassName());
}
//Field별 Form Datas 처리용

View File

@ -2,6 +2,7 @@
namespace App\Controllers\Admin;
use App\Models\UserModel;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;
@ -10,9 +11,9 @@ class UserController extends AdminController
{
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
{
$this->_backend = service('user');
$this->_model = new UserModel();
parent::initController($request, $response, $logger);
$this->_viewPath .= strtolower($this->_backend->getClassName());
$this->_viewPath .= strtolower($this->_model->getClassName());
}
//Field별 Form Datas 처리용

View File

@ -2,6 +2,7 @@
namespace App\Controllers\Admin;
use App\Models\UserSNSModel;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;
@ -10,8 +11,8 @@ class UserSNSController extends AdminController
{
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
{
$this->_backend = service('usersns');
$this->_model = new UserSNSModel();
parent::initController($request, $response, $logger);
$this->_viewPath .= strtolower($this->_backend->getClassName());
$this->_viewPath .= strtolower($this->_model->getClassName());
}
}

View File

@ -48,7 +48,7 @@ abstract class BaseController extends Controller
/**
* Constructor.
*/
protected $_backend = null;
protected $_model = null;
protected $_session = null;
protected $_viewPath = '';
protected $_viewDatas = array();
@ -60,9 +60,9 @@ abstract class BaseController extends Controller
// E.g.: $this->session = \Config\Services::session();
$this->_session = \Config\Services::session();
$this->_viewDatas['layout'] = LAYOUTS['empty'];
$this->_viewDatas['title'] = lang($this->_backend->getClassName() . '.title');
$this->_viewDatas['title'] = lang($this->_model->getClassName() . '.title');
$this->_viewDatas['session'] = $this->_session;
helper($this->_backend->getClassName());
helper($this->_model->getClassName());
}
//Field별 Form Datas 처리용
@ -121,15 +121,14 @@ abstract class BaseController extends Controller
$action = 'update';
break;
}
$this->_viewDatas['fields'] = $fields ?: $this->_backend->getFields($action);
$this->_viewDatas['fieldRules'] = $this->_backend->getFieldRules($this->_viewDatas['fields'], $action);
$this->_viewDatas['fieldFilters'] = $this->_backend->getFieldFilters();
$this->_viewDatas['batchjobFilters'] = $this->_backend->getFieldBatchFilters();
$this->_viewDatas['fieldFormOptions'] = $this->_backend->getFieldFormOptions($this->_viewDatas['fieldFilters']);
$this->_viewDatas['fields'] = $fields ?: $this->_model->getFields($action);
$this->_viewDatas['fieldRules'] = $this->_model->getFieldRules($this->_viewDatas['fields'], $action);
$this->_viewDatas['fieldFilters'] = $this->_model->getFieldFilters();
$this->_viewDatas['batchjobFilters'] = $this->_model->getFieldBatchFilters();
$this->_viewDatas['fieldFormOptions'] = $this->_model->getFieldFormOptions($this->_viewDatas['fieldFilters']);
return $this->_viewDatas;
}
//Insert관련
final public function insert_form()
{
@ -140,6 +139,7 @@ abstract class BaseController extends Controller
$this->_session->keepFlashdata(SESSION_NAMES['RETURN_URL']);
return view($this->_viewPath . '/insert', $this->_viewDatas);
} catch (\Exception $e) {
log_message("error", $e->getMessage());
return redirect()->to($this->_session->getFlashdata(SESSION_NAMES['RETURN_URL']))->with('return_message', $e->getMessage());
}
}
@ -161,7 +161,7 @@ abstract class BaseController extends Controller
try {
$this->_viewDatas = $this->init(__FUNCTION__);
$this->insert_process();
$entity = $this->_backend->insert($this->_viewDatas['fieldDatas']);
$entity = $this->_model->insert($this->_viewDatas['fieldDatas']);
$msg = "{$this->_viewDatas['title']}에서 {$entity->getTitle()}" . __FUNCTION__ . " 완료하였습니다.";
return redirect()->to($this->_session->getFlashdata(SESSION_NAMES['RETURN_URL']));
} catch (\Exception $e) {
@ -181,9 +181,10 @@ abstract class BaseController extends Controller
$this->_viewDatas['forms'] = ['attributes' => ['method' => "post",], 'hiddens' => []];
helper(['form']);
$this->_session->keepFlashdata(SESSION_NAMES['RETURN_URL']);
$this->_viewDatas['entity'] = $this->_backend->getEntity($uid);
$this->_viewDatas['entity'] = $this->_model->getEntity($uid);
return view($this->_viewPath . '/update', $this->_viewDatas);
} catch (\Exception $e) {
log_message("error", $e->getMessage());
return redirect()->to($this->_session->getFlashdata(SESSION_NAMES['RETURN_URL']))->with('return_message', $e->getMessage());
}
}
@ -208,9 +209,9 @@ abstract class BaseController extends Controller
$msg = "";
try {
$this->_viewDatas = $this->init(__FUNCTION__);
$entity = $this->_viewDatas['entity'] = $this->_backend->getEntity($uid);
$entity = $this->_viewDatas['entity'] = $this->_model->getEntity($uid);
$this->update_process();
$entity = $this->_backend->update($entity, $this->_viewDatas['fieldDatas']);
$entity = $this->_model->update($entity, $this->_viewDatas['fieldDatas']);
$msg = "{$this->_viewDatas['title']}에서 {$entity->getTitle()}" . __FUNCTION__ . " 완료하였습니다.";
return redirect()->to($this->_session->getFlashdata(SESSION_NAMES['RETURN_URL']));
} catch (\Exception $e) {
@ -230,14 +231,15 @@ abstract class BaseController extends Controller
$this->_viewDatas['forms'] = ['attributes' => ['method' => "post",], 'hiddens' => []];
helper(['form']);
$this->_session->keepFlashdata(SESSION_NAMES['RETURN_URL']);
$entity = $this->_backend->getEntity($uid);
$titleField = $this->_backend->getTitleField();
$entity = $this->_model->getEntity($uid);
$titleField = $this->_model->getTitleField();
$entity->$titleField = "RE: " . $entity->$titleField;
$contentField = $this->_backend->getContentField();
$contentField = $this->_model->getContentField();
$entity->$contentField .= "\n----------------------------------------------\n";
$this->_viewDatas['entity'] = $entity;
return view($this->_viewPath . '/reply', $this->_viewDatas);
} catch (\Exception $e) {
log_message("error", $e->getMessage());
return redirect()->to($this->_session->getFlashdata(SESSION_NAMES['RETURN_URL']))->with('return_message', $e->getMessage());
}
}
@ -250,9 +252,9 @@ abstract class BaseController extends Controller
$msg = "";
try {
$this->_viewDatas = $this->init(__FUNCTION__);
$entity = $this->_viewDatas['entity'] = $this->_backend->getEntity($uid);
$entity = $this->_viewDatas['entity'] = $this->_model->getEntity($uid);
$this->reply_process();
$entity = $this->_backend->reply($entity, $this->_viewDatas['fieldDatas']);
$entity = $this->_model->reply($entity, $this->_viewDatas['fieldDatas']);
$msg = "{$this->_viewDatas['title']}에서 {$entity->getTitle()}" . __FUNCTION__ . " 완료하였습니다.";
return redirect()->to($this->_session->getFlashdata(SESSION_NAMES['RETURN_URL']));
} catch (\Exception $e) {
@ -274,16 +276,17 @@ abstract class BaseController extends Controller
$msg = "";
try {
$this->_viewDatas = $this->init(__FUNCTION__, [$field]);
$entity = $this->_viewDatas['entity'] = $this->_backend->getEntity($uid);
$entity = $this->_viewDatas['entity'] = $this->_model->getEntity($uid);
$this->toggle_process();
$entity = $this->_backend->update($entity, $this->_viewDatas['fieldDatas']);
$entity = $this->_model->update($entity, $this->_viewDatas['fieldDatas']);
$msg = "{$this->_viewDatas['title']}에서 {$entity->getTitle()}" . __FUNCTION__ . " 완료하였습니다.";
return redirect()->to($this->_session->getFlashdata(SESSION_NAMES['RETURN_URL']));
} catch (\Exception $e) {
$msg = "{$this->_viewDatas['title']}에서 " . __FUNCTION__ . " 실패하였습니다.\n" . $e->getMessage();
log_message("error", $e->getMessage());
return redirect()->to($this->_session->getFlashdata(SESSION_NAMES['RETURN_URL']));
} finally {
$this->_session->setFlashdata("return_message", $msg);
return redirect()->to($this->_session->getFlashdata(SESSION_NAMES['RETURN_URL']));
}
}
//Batchjob 관련
@ -299,7 +302,7 @@ abstract class BaseController extends Controller
try {
//fields 해당하는 field중 선택된 값이 있는경우만 fields로 정의
$fields = array();
foreach ($this->_backend->getFieldBatchFilters() as $field) {
foreach ($this->_model->getFieldBatchFilters() as $field) {
if ($this->request->getVar($field)) {
array_push($fields, $field);
}
@ -312,12 +315,12 @@ abstract class BaseController extends Controller
$cnt = 1;
//Transaction 시작
$this->_backend->transStart();
$this->_model->transStart();
foreach ($uids as $uid) {
try {
$entity = $this->_viewDatas['entity'] = $this->_backend->getEntity($uid);
$entity = $this->_viewDatas['entity'] = $this->_model->getEntity($uid);
$this->batchjob_process();
array_push($entitys, $this->_backend->update($entity, $this->_viewDatas['fieldDatas']));
array_push($entitys, $this->_model->update($entity, $this->_viewDatas['fieldDatas']));
array_push($batchjobs, "{$cnt}. {$uid}->{$entity->getTitle()}는 완료.");
} catch (\Exception $e) {
array_push($batchjobs, "{$cnt}. {$uid}는 실패.");
@ -325,16 +328,17 @@ abstract class BaseController extends Controller
$cnt++;
}
//Transaction Commit
$this->_backend->transCommit();
$this->_model->transCommit();
$msg = sprintf(
"%s에서 총:%s개의 %s 완료하였습니다.",
$this->_viewDatas['title'],
count($entitys),
__FUNCTION__
);
return redirect()->to($this->_session->getFlashdata(SESSION_NAMES['RETURN_URL']));
} catch (\Exception $e) {
//Transaction Rollback
$this->_backend->transRollback();
$this->_model->transRollback();
log_message('error', sprintf("---------batchjob 작업결과--------\n%s\n", implode("\n", $batchjobs)));
return sprintf(
"총:%s개의 작업중 %s개는 성공하였지만 , %s개가 실패하여 %s 취소되었습니다.\n%s",
@ -344,9 +348,9 @@ abstract class BaseController extends Controller
__FUNCTION__,
);
log_message("error", $e->getMessage());
return redirect()->to($this->_session->getFlashdata(SESSION_NAMES['RETURN_URL']));
} finally {
$this->_session->setFlashdata("return_message", $msg);
return redirect()->to($this->_session->getFlashdata(SESSION_NAMES['RETURN_URL']));
}
}
@ -355,14 +359,20 @@ abstract class BaseController extends Controller
{
$msg = "";
try {
$entity = $this->_backend->delete($this->_backend->getEntity($uid));
$entity = $this->_model->delete($this->_model->getEntity($uid));
if (!$this->_model->delete($entity->getPrimaryKey())) {
log_message("error", __FUNCTION__ . "에서 호출:" . $this->_model->getLastQuery());
log_message("error", implode("\n", $this->_model->errors()));
throw new \Exception(__FUNCTION__ . " 오류 발생.\n" . var_export($this->_model->errors(), true));
}
$msg = "{$this->_viewDatas['title']}에서 {$entity->getTitle()}" . __FUNCTION__ . " 완료하였습니다.";
return redirect()->to($this->_session->getFlashdata(SESSION_NAMES['RETURN_URL']));
} catch (\Exception $e) {
$msg = "{$this->_viewDatas['title']}에서 " . __FUNCTION__ . " 실패하였습니다.\n" . $e->getMessage();
log_message("error", $e->getMessage());
return redirect()->to($this->_session->getFlashdata(SESSION_NAMES['RETURN_URL']));
} finally {
$this->_session->setFlashdata("return_message", $msg);
return redirect()->to($this->_session->getFlashdata(SESSION_NAMES['RETURN_URL']));
}
}
@ -377,8 +387,8 @@ abstract class BaseController extends Controller
$this->_viewDatas = $this->init(__FUNCTION__);
helper(['form']);
$this->_viewDatas['forms'] = ['attributes' => ['method' => "post",], 'hiddens' => []];
$entity = $this->_viewDatas['entity'] = $this->_backend->getEntity($uid);
$this->_viewDatas['entity'] = $this->_backend->view($entity);
$entity = $this->_viewDatas['entity'] = $this->_model->getEntity($uid);
$this->_viewDatas['entity'] = $this->_model->view($entity);
$this->_session->keepFlashdata(SESSION_NAMES['RETURN_URL']);
return view($this->_viewPath . '/view', $this->_viewDatas);
} catch (\Exception $e) {
@ -393,7 +403,7 @@ abstract class BaseController extends Controller
// 2.app/Config/Pager.php/$templates에 'bootstrap_full => 'Pagers\bootstrap_full',
// 'bootstrap_simple' => 'Pagers\bootstrap_simple', 추가
$pager = \Config\Services::pager();
// $this->_backend->paginate($this->_viewDatas['per_page'], $pager_group, $this->_viewDatas['page'], $segment);
// $this->_model->paginate($this->_viewDatas['per_page'], $pager_group, $this->_viewDatas['page'], $segment);
$pager->makeLinks(
$this->_viewDatas['page'],
$this->_viewDatas['per_page'],
@ -420,12 +430,12 @@ abstract class BaseController extends Controller
$end = $this->request->getVar('end');
$order_field = $this->request->getVar('order_field');
$order_value = $this->request->getVar('order_value');
$this->_backend->setCondition($filterFields, $word, $start, $end, $order_field, $order_value);
$this->_model->setCondition($filterFields, $word, $start, $end, $order_field, $order_value);
}
private function index_getEntitys(int $page = 0, int $per_page = 0)
{
$this->index_setCondition();
return $this->_backend->getFindEntitys($page, $per_page);
return $per_page ? $this->_model->findAll($per_page, $page * $per_page - $per_page) : $this->_model->findAll();
}
public function index()
{
@ -446,7 +456,7 @@ abstract class BaseController extends Controller
$this->_viewDatas['uri'] = $this->request->getUri();
//Totalcount 처리
$this->index_setCondition();
$this->_viewDatas['total_count'] = $this->_backend->getTotalCount();
$this->_viewDatas['total_count'] = $this->_model->countAllResults();
//줄수 처리용
$this->_viewDatas['pageOptions'] = array("" => "줄수선택");
for ($i = 10; $i <= $this->_viewDatas['total_count'] + $this->_viewDatas['per_page']; $i += 10) {
@ -456,7 +466,7 @@ abstract class BaseController extends Controller
$this->_viewDatas['pagination'] = $this->index_getPagination();
//모델 처리
$this->_viewDatas['entitys'] = $this->index_getEntitys((int)$this->_viewDatas['page'], (int)$this->_viewDatas['per_page']);
// log_message("debug", __METHOD__ . "에서 호출:" . $this->_backend->getLastQuery());
// log_message("debug", __METHOD__ . "에서 호출:" . $this->_model->getLastQuery());
//setting return_url to session flashdata
$this->_session->setFlashdata(SESSION_NAMES['RETURN_URL'], current_url() . '?' . $this->request->getUri()->getQuery() ?: "");
return view($this->_viewPath . '/index', $this->_viewDatas);
@ -474,7 +484,7 @@ abstract class BaseController extends Controller
//Header용
$column = 'A';
foreach ($viewDatas['fields'] as $field) {
$sheet->setCellValue($column++ . '1', lang($this->_backend->getClassName() . '.label.' . $field));
$sheet->setCellValue($column++ . '1', lang($this->_model->getClassName() . '.label.' . $field));
}
//본문용
$line = 2;
@ -515,7 +525,7 @@ abstract class BaseController extends Controller
final public function download(string $field, $uid)
{
try {
$entity = $this->_backend->getEntity($uid);
$entity = $this->_model->getEntity($uid);
if (!$entity->$field) {
throw new \Exception("첨부파일이 확인되지 않습니다.");
}

View File

@ -7,9 +7,9 @@ use App\Entities\BaseEntity;
//계층형구조구현용 모델(게시판,카테고리 등등)
abstract class BaseHierarchyModel extends BaseModel
{
protected function __construct()
protected function __construct(string $className)
{
parent::__construct();
parent::__construct($className);
$this->allowedFields = [...$this->allowedFields, "grpno", "grporder", "grpdepth"];
$this->validationRules = [...$this->validationRules,];
}

View File

@ -40,9 +40,12 @@ abstract class BaseModel extends Model
protected $beforeDelete = [];
protected $afterDelete = [];
private $_className = null;
private $_user_options = null;
protected $_session = null;
protected function __construct()
protected function __construct(string $className)
{
$this->_className = $className;
parent::__construct();
$this->allowedFields = ["updated_at", "created_at"];
if (!$this->useAutoIncrement) {
@ -51,6 +54,10 @@ abstract class BaseModel extends Model
$this->validationRules = [];
$this->_session = \Config\Services::session();
}
final public function getClassName()
{
return $this->_className;
}
final public function getPrimaryKey(): string
{
return $this->primaryKey;
@ -111,13 +118,45 @@ abstract class BaseModel extends Model
return $this->getFieldFilters();
}
public function getFieldFormOptions($conditions, $options = array()): array
//Field별 Form Option용
public function getFormOptions($conditions, $options = array()): array
{
foreach ($this->getEntitys($conditions) as $entity) {
foreach ($this->getEntitys(['status' => 'use']) as $entity) {
$options[$entity->getPrimaryKey()] = $entity->getTitle();
}
return $options;
}
public function getFieldFormOption(string $field): array
{
switch ($field) {
case 'user_uid':
if (is_null($this->_user_options)) {
$userModel = new UserModel();
$this->_user_options = $userModel->getFormOptions(['status' => 'use']);
}
$options = $this->_user_options;
break;
default:
$options = lang($this->_className . '.' . strtoupper($field));
break;
}
if (!is_array($options)) {
throw new \Exception(__FUNCTION__ . "에서 {$this->_className}의 Field:{$field}의 FormOptionData가 array가 아닙니다.\n" . var_export($options, true));
}
return $options;
}
//Field별 Form Option용
final public function getFieldFormOptions(array $fields): array
{
$fieldFormOptions = array();
foreach ($fields as $field) {
if (!is_string($field)) {
throw new \Exception(__FUNCTION__ . "에서 {$this->_className}의 Field:{$field}가 string 아닙니다.\n" . var_export($fields, true));
}
$fieldFormOptions[$field] = $this->getFieldFormOption($field);
}
return $fieldFormOptions;
}
final public function getUUID()
{
@ -238,4 +277,17 @@ abstract class BaseModel extends Model
$this->orderBy($field ?: $this->primaryKey, $order ?: "DESC");
}
}
final public function setCondition(array $filterFields, $word, $start, $end, $order_field, $order_value)
{
foreach ($filterFields as $field => $value) {
$this->where($field, $value);
}
if (!is_null($word)) {
$this->setIndexWordFilter($word);
}
if (!is_null($start) && !is_null($end)) {
$this->setIndexDateFilter($start, $end);
}
$this->setIndexOrderBy($order_field, $order_value);
}
}

View File

@ -11,7 +11,7 @@ class BoardConfigModel extends BaseModel
protected $returnType = BoardConfigEntity::class;
public function __construct()
{
parent::__construct();
parent::__construct('BoardConfig');
$this->allowedFields = [...$this->allowedFields, ...$this->getFields()];
$this->validationRules = [...$this->validationRules, ...$this->getFieldRules($this->allowedFields),];
}

View File

@ -6,12 +6,12 @@ use App\Entities\BoardEntity;
class BoardModel extends BaseHierarchyModel
{
//BaseHierarchyModel를 확장하면 grpno가 숫자이고, primarykey를 대분류 생성시 copy하여 grpno에 넣고 sorting하므로
private $_boardconfig_options = null;
protected $table = "tw_board";
protected $returnType = BoardEntity::class;
public function __construct()
{
parent::__construct();
parent::__construct('Board');
$this->allowedFields = [...$this->allowedFields, ...$this->getFields(), "user_uid"];
$this->validationRules = [...$this->validationRules, ...$this->getFieldRules($this->allowedFields),];
}
@ -69,6 +69,26 @@ class BoardModel extends BaseHierarchyModel
}
return $rules;
}
//Field별 Form Option용
public function getFieldFormOption(string $field): array
{
switch ($field) {
case 'board_config_uid':
if (is_null($this->_boardconfig_options)) {
$boardConfigModel = new BoardConfigModel();
$this->_boardconfig_options = $boardConfigModel->getFormOptions(['status' => 'use']);
}
$options = $this->_boardconfig_options;
break;
default:
return parent::getFieldFormOption($field);
break;
}
if (!is_array($options)) {
throw new \Exception(__FUNCTION__ . "에서 {$this->_className}의 Field:{$field}의 FormOptionData가 array가 아닙니다.\n" . var_export($options, true));
}
return $options;
}
public function getEntity($conditions): BoardEntity
{

View File

@ -11,7 +11,7 @@ class CategoryModel extends BaseHierarchyModel
protected $returnType = CategoryEntity::class;
public function __construct()
{
parent::__construct();
parent::__construct('Category');
$this->allowedFields = [...$this->allowedFields, ...$this->getFields(),];
$this->validationRules = [...$this->validationRules, ...$this->getFieldRules($this->allowedFields),];
}
@ -69,7 +69,7 @@ class CategoryModel extends BaseHierarchyModel
return $this->where($conditions)->first() ?: throw new \Exception("해당 데이터가 없습니다.\n" . var_export($conditions, true));
}
public function getFieldFormOptions($conditions, $options = array()): array
public function getFormOptions($conditions, $options = array()): array
{
$old_title = "";
foreach ($this->where($conditions)->orderby("grpno DESC, grporder ASC")->findAll() as $entity) {

View File

@ -13,7 +13,7 @@ class OrderModel extends BaseModel
protected $useSoftDeletes = false;
public function __construct()
{
parent::__construct();
parent::__construct('Order');
$this->allowedFields = ["uid", "user_uid", "sess_id", ...$this->allowedFields, ...$this->getFields(),];
$this->validationRules = [...$this->validationRules, ...$this->getFieldRules($this->allowedFields),];
}

View File

@ -6,13 +6,14 @@ use App\Entities\ProductEntity;
class ProductModel extends BaseModel
{
private $_category_options = null;
protected $table = "tw_product";
protected $useAutoIncrement = false;
protected $returnType = ProductEntity::class;
protected $useSoftDeletes = false;
public function __construct()
{
parent::__construct();
parent::__construct('Product');
$this->allowedFields = ["uid", "user_uid", ...$this->allowedFields, ...$this->getFields(),];
$this->validationRules = [...$this->validationRules, ...$this->getFieldRules($this->allowedFields),];
}
@ -77,6 +78,27 @@ class ProductModel extends BaseModel
return $rules;
}
//Field별 Form Option용
public function getFieldFormOption(string $field): array
{
switch ($field) {
case 'category_uid':
if (is_null($this->_category_options)) {
$categoryModel = new CategoryModel();
$this->_category_options = $categoryModel->getFormOptions(['status' => 'use']);
}
$options = $this->_category_options;
break;
default:
return parent::getFieldFormOption($field);
break;
}
if (!is_array($options)) {
throw new \Exception(__FUNCTION__ . "에서 {$this->getClassName()}의 Field:{$field}의 FormOptionData가 array가 아닙니다.\n" . var_export($options, true));
}
return $options;
}
public function getEntity($conditions): ProductEntity
{
return $this->where($conditions)->first() ?: throw new \Exception("해당 데이터가 없습니다.\n" . var_export($conditions, true));

View File

@ -12,7 +12,7 @@ class UserModel extends BaseModel
protected $useSoftDeletes = false;
public function __construct()
{
parent::__construct();
parent::__construct('User');
$this->allowedFields = ["uid", ...$this->allowedFields, ...$this->getFields()];
$this->validationRules = [...$this->validationRules, ...$this->getFieldRules($this->allowedFields),];
}

View File

@ -10,7 +10,7 @@ class UserSNSModel extends BaseModel
protected $returnType = UserSNSEntity::class;
public function __construct()
{
parent::__construct();
parent::__construct('UserSNS');
$this->allowedFields = [...$this->allowedFields, ...$this->getFields(), "user_uid"];
$this->validationRules = [...$this->validationRules, ...$this->getFieldRules($this->allowedFields),];
}

View File

@ -1,28 +1,18 @@
<?php
namespace App\Backend;
namespace App\Service;
use App\Models\OrderModel;
use App\Models\ProductModel;
class EcommerceBackend extends BaseBackend
class EcommerceService
{
private $_product = null;
private $_order = null;
private $_productModel = null;
private $_orderModel = null;
public function __construct()
{
parent::__construct('Ecommerce');
$this->_product = new ProductBackend();
$this->_order = new OrderBackend();
}
final public function getOrderBackend()
{
$this->_order;
}
final public function getProductBackend()
{
$this->_product;
$this->_productModel = new ProductModel();
$this->_orderModel = new OrderModel();
}
//Form Fields
@ -56,8 +46,8 @@ class EcommerceBackend extends BaseBackend
//장바구니에 담기
public function addCart(array $fieldDatas)
{
$product = $this->_product->getEntity($fieldDatas['product_uid']);
$this->_product->addCart($product, $fieldDatas['quantity'], $fieldDatas['price']);
$this->_order->addCart($product, $fieldDatas['quantity'], $fieldDatas['price']);
$product = $this->_productModel->getEntity($fieldDatas['product_uid']);
$this->_productModel->addCart($product, $fieldDatas['quantity'], $fieldDatas['price']);
$this->_orderModel->addCart($product, $fieldDatas['quantity'], $fieldDatas['price']);
}
}