pdo 확장git clone --branch 3.x https://github.com/gueff/myMVC.git myMVC_3.x기본 모듈의 구성 폴더에서 DB 구성을 만듭니다. (@see https://mymvc.ueffing.net/3.3.x/configuration#modules-config-folder)
환경 develop 위한 DB 구성 예
//-------------------------------------------------------------------------------------
// Module DB
$ aConfig [ ' MODULE ' ][ ' DB ' ] = array (
' db ' => array (
' type ' => ' mysql ' ,
' host ' => ' 127.0.0.1 ' ,
' port ' => 3306 ,
' username ' => getenv ( ' db.username ' ),
' password ' => getenv ( ' db.password ' ),
' dbname ' => getenv ( ' db.dbname ' ),
' charset ' => ' utf8 '
),
' caching ' => array (
' enabled ' => true ,
' lifetime ' => ' 7200 '
),
' logging ' => array (
' log_output ' => ' FILE ' ,
// consider to turn it on for develop and test environments only
' general_log ' => strtoupper ( ' on ' ), # on | off
// 1) make sure write access is given to the folder
// as long as the db user is going to write and not the webserver user
// 2) consider a logrotate mechanism for this logfile as it may grow quickly
' general_log_file ' => ' /tmp/ ' . getenv ( ' db.dbname ' ) . ' .log ' ,
)
);getenv() 를 사용합니다. 즉, 비밀을 /.env 파일에 저장합니다.DB 테이블의 표현으로서 PHP 클래스
파일 : modules/Foo/Model/Table/User.php
<?php
namespace Foo Model Table ;
use DB Model Db ;
class User extends Db
{
/**
* @var array
*/
protected $ aField = array (
' email ' => " varchar(255) COLLATE utf8_general_ci NOT NULL " ,
' active ' => " int(1) DEFAULT '0' NOT NULL " ,
' uuid ' => " varchar(36) COLLATE utf8_general_ci COMMENT 'uuid permanent' NOT NULL " ,
' uuidtmp ' => " varchar(36) COLLATE utf8_general_ci COMMENT 'uuid; changes on create|login' NOT NULL " ,
' password ' => " varchar(60) COLLATE utf8_general_ci COMMENT 'password_hash()' NOT NULL " ,
' nickname ' => " varchar(10) COLLATE utf8_general_ci NOT NULL " ,
' forename ' => " varchar(25) COLLATE utf8_general_ci NOT NULL " ,
' lastname ' => " varchar(25) COLLATE utf8_general_ci NOT NULL " ,
);
/**
* @param array $aDbConfig
* @throws ReflectionException
*/
public function __construct ( array $ aDbConfig = array ())
{
// basic creation of the table
parent :: __construct (
$ this -> aField ,
$ aDbConfig
);
}
}FooModelTableUser 를 만듭니다email 에서 여러 필드가 있습니다 ... 부동산에 선언 된 lastname $aFieldid , stampChange 및 stampCreate 자동으로 추가됩니다.DataType/DTFooModelTableUser.php 생성합니다테이블 생성 및 외국 키 추가
파일 : modules/Foo/Model/Table/User.php
<?php
namespace Foo Model Table ;
use DB Model Db ;
use DB DataType DB Foreign ;
class User extends Db
{
/**
* @var array
*/
protected $ aField = array (
' email ' => " varchar(255) COLLATE utf8_general_ci NOT NULL " ,
' active ' => " int(1) DEFAULT '0' NOT NULL " ,
' uuid ' => " varchar(36) COLLATE utf8_general_ci COMMENT 'uuid permanent' NOT NULL " ,
' uuidtmp ' => " varchar(36) COLLATE utf8_general_ci COMMENT 'uuid; changes on create|login' NOT NULL " ,
' password ' => " varchar(60) COLLATE utf8_general_ci COMMENT 'password_hash()' NOT NULL " ,
' nickname ' => " varchar(10) COLLATE utf8_general_ci NOT NULL " ,
' forename ' => " varchar(25) COLLATE utf8_general_ci NOT NULL " ,
' lastname ' => " varchar(25) COLLATE utf8_general_ci NOT NULL " ,
);
/**
* @param array $aDbConfig
* @throws ReflectionException
*/
public function __construct ( array $ aDbConfig = array ())
{
// basic creation of the table
parent :: __construct (
$ this -> aField ,
$ aDbConfig
);
$ this -> setForeignKey (
Foreign:: create ()
-> set_sForeignKey ( ' id_FooModelTableGroup ' )
-> set_sReferenceTable ( ' FooModelTableGroup ' )
);
}
}FooModelTableUser 를 만듭니다email 에서 여러 필드가 있습니다 ... 부동산에 선언 된 lastname $aFieldid , stampChange 및 stampCreate 자동으로 추가됩니다.id_FooModelTableGroup 테이블에 대한 포인팅 FooModelTableGroup - Method setForeignKey() 에 의해 추가됩니다.DataType/DTFooModelTableUser.php 생성합니다 파일 : modules/Foo/Model/DB.php
<?php
/**
* - register your db table classes as static properties.
* - add a doctype to each static property
* - these doctypes must contain the vartype information about the certain class
* @example
* @var FooModelTableUser
* public static $oFooModelTableUser;
* ---
* [!] it is important to declare the vartype expanded with a full path
* avoid to make use of `use ...` support
* otherwise the classes could not be read correctly
*/
namespace Foo Model ;
use DB Model DbInit ;
use DB Trait DbInitTrait ;
class DB extends DbInit
{
use DbInitTrait;
/**
* @var FooModelTableUser
*/
public static $ oFooModelTableUser ;
} MyMVC 모듈의 이벤트 폴더에서 파일 db.php (원하는대로 이름을 지정할 수 있음)를 작성하고 바인딩을 다음과 같이 선언합니다.
file /modules/{MODULE}/etc/event/db.php
<?php
MVC Event:: processBindConfigStack ([
// let create an openapi yaml file
// according to DB Table DataType Classes
// when the DataBase Tables setup changes
' db.model.db.construct.saveCache ' => array (
function ( string $ sTableName = '' ) {
// one-timer
if ( false === MVC Registry:: isRegistered ( ' DB::openapi ' ))
{
MVC Registry:: set ( ' DB::openapi ' , true );
// generate /modules/{MODULE}/DataType/DTTables.yaml
$ sYamlFile = DB Model Openapi:: createDTYamlOnDTClasses (
// pass instance of your concrete DB Class
Foo Model DB :: init ()
);
}
}
),
]); 메인 컨트롤러 클래스에서는 DBINIT 클래스의 새로운 인스턴스를 만듭니다. 좋은 장소는 __construct() 메소드입니다.
namespace Foo Controller ;
use Foo Model DB ;
public function __construct ()
{
DB :: init ();
}그런 다음 프론트 엔드 템플릿에서도 어디에서나 식탁보에 액세스 할 수 있습니다.
용법
DB :: $ oFooModelTableUser ->. . .<method> . . . 따라서 ( create ) 관련 데이터 유형의 객체는 create 메소드에 주어져야합니다. 예를 들어 "dtfoomodeltableUser"to Tableclass "모듈/foo/model/db/tableUser":
DB :: $ oFooModelTableUser -> create (
DTFooModelTableUser:: create ()
-> set_id_FooModelTableGroup ( 1 )
-> set_uuid (Strings:: uuid4 ())
-> set_email ( ' [email protected] ' )
-> set_forename ( ' foo ' )
-> set_lastname ( ' bar ' )
-> set_nickname ( ' foo ' )
-> set_password ( password_hash ( ' ...password... ' , PASSWORD_DEFAULT ))
-> set_active ( 1 )
-> set_stampChange ( date ( ' Y-m-d H:i:s ' ))
-> set_stampCreate ( date ( ' Y-m-d H:i:s ' ))
); retrieveTupel 특정 Tupel을 요청하고 요청 된 테이블에 따라 데이터 유형 객체를 반환합니다.
retrieveTupel id 로 식별
/** @var FooDataTypeDTFooModelTableUser $oDTFooModelTableUser */
$ oDTFooModelTableUser = DB :: $ oFooModelTableUser -> retrieveTupel (
DTFooModelTableUser:: create ()
-> set_id ( 2 )
) retrieve 요청 된 테이블에 따라 데이터 유형 객체 배열을 반환합니다.
retrieve : 모든 데이터 세트를 가져옵니다
/** @var FooDataTypeDTFooModelTableUser[] $aDTFooModelTableUser */
$ aDTFooModelTableUser = DB :: $ oFooModelTableUser -> retrieveTupel (); retrieve : 특정 데이터 세트를 얻습니다
/** @var FooDataTypeDTFooModelTableUser[] $aDTFooModelTableUser */
$ aDTFooModelTableUser = DB :: $ oFooModelTableUser -> retrieve (
DTArrayObject:: create ()
-> add_aKeyValue (
DTKeyValue:: create ()
-> set_sKey ( ' stampChange ' )
-> set_mOptional1 ( ' LIKE ' )
-> set_sValue ( ' 2021-06-19 ' )
);
); retrieve : 정렬 순서로 데이터 세트를 가져옵니다
/** @var FooDataTypeDTFooModelTableUser[] $aDTFooModelTableUser */
$ aDTFooModelTableUser = DB :: $ oFooModelTableUser -> retrieve (
DTArrayObject:: create ()
-> add_aKeyValue (
DTKeyValue:: create ()
-> set_sKey ( ' email ' )
-> set_mOptional1 ( ' LIKE ' )
-> set_sValue ( ' %@example.com% ' )
),
DTArrayObject:: create ()
-> add_aKeyValue (
DTKeyValue:: create ()
-> set_sValue ( ' ORDER BY id ASC ' )
)
); retrieve : 처음 30 개의 데이터 세트 받기 (제한 0,30)
/** @var FooDataTypeDTFooModelTableUser[] $aDTFooModelTableUser */
$ aDTFooModelTableUser = DB :: $ oFooModelTableUser -> retrieve (
null ,
DTArrayObject:: create ()
-> add_aKeyValue (
DTKeyValue:: create ()
-> set_sValue ( ' LIMIT 0,30 ' )
)
) updateTupel : 특정 Tupel 업데이트 - id 로 식별
// get Tupel
/** @var FooDataTypeDTFooModelTableUser $oDTFooModelTableUser */
$ oDTFooModelTableUser = DB :: $ oFooModelTableUser -> retrieveTupel (
DTFooModelTableUser:: create ()-> set_id ( 2 )
)
// modify Tupel
$ oDTFooModelTableUser-> set_nickname ( ' XYZ ' );
// update Tupel
/** @var boolean $bSuccess */
$ bSuccess = DB :: $ oFooModelTableUser -> updateTupel (
$ oDTFooModelTableUser
);id 와 동등한 데이터 세트 Tupel이 업데이트됩니다. update : WHERE 절에 영향을받는 모든 Tupel 업데이트
/** @var boolean $bSuccess */
$ bSuccess = DB :: $ oFooModelTableUser -> update (
DTFooModelTableUser:: create ()
-> set_active ( ' 1 ' ),
// where
DTArrayObject:: create ()
-> add_aKeyValue (
DTKeyValue:: create ()
-> set_sKey ( ' active ' )
-> set_mOptional1 ( ' = ' )
-> set_sValue ( ' 0 ' )
)
); deleteTupel :이 특정 Tupel id 로 식별
/** @var boolean $bSuccess */
$ bSuccess = DB :: $ oFooModelTableUser -> deleteTupel (
DTFooModelTableUser:: create ()
-> set_id ( 2 )
) delete : WHERE 절에 영향을받는 모든 Tupel 삭제
$ bSuccess = DB :: $ oFooModelTableUser -> delete (
// where
DTArrayObject:: create ()
-> add_aKeyValue (
DTKeyValue:: create ()
-> set_sKey ( ' stampCreate ' )
-> set_mOptional1 ( ' < ' )
-> set_sValue ( ' 2023-06-19 00:00:00 ' )
)
); // Amount of all Datasets
$ iAmount = DB :: $ oFooModelTableUser -> count ();
// Amount of specific Datasets
$ iAmount = DB :: $ oFooModelTableUser -> count (
DTArrayObject:: create ()
-> add_aKeyValue (
DTKeyValue:: create ()
-> set_sKey ( ' stampChange ' )
-> set_mOptional1 ( ' = ' )
-> set_sValue ( ' 2021-06-19 ' )
)
); // Returns a checksum of the table
$ iChecksum = DB :: $ oFooModelTableUser -> checksum ();테이블 필드 정보로 배열을 반환합니다
$ aFieldInfo = DB :: $ oFooModelTableUser -> getFieldInfo ();예제 반환
// type: array, items: 9
[
'id_FooModelTableGroup' => [
'Field' => 'id_FooModelTableGroup',
'Type' => 'int(11)',
'Null' => 'YES',
'Key' => 'MUL',
'Default' => NULL,
'Extra' => '',
'php' => 'int',
],
'email' => [
'Field' => 'email',
'Type' => 'varchar(255)',
'Null' => 'NO',
'Key' => '',
'Default' => NULL,
'Extra' => '',
'php' => 'string',
],
'active' => [
'Field' => 'active',
'Type' => 'int(1)',
'Null' => 'NO',
'Key' => '',
'Default' => '0',
'Extra' => '',
'php' => 'int',
],
'uuid' => [
'Field' => 'uuid',
'Type' => 'varchar(36)',
'Null' => 'NO',
'Key' => '',
'Default' => NULL,
'Extra' => '',
'php' => 'string',
],
'uuidtmp' => [
'Field' => 'uuidtmp',
'Type' => 'varchar(36)',
'Null' => 'NO',
'Key' => '',
'Default' => NULL,
'Extra' => '',
'php' => 'string',
],
'password' => [
'Field' => 'password',
'Type' => 'varchar(60)',
'Null' => 'NO',
'Key' => '',
'Default' => NULL,
'Extra' => '',
'php' => 'string',
],
'nickname' => [
'Field' => 'nickname',
'Type' => 'varchar(10)',
'Null' => 'NO',
'Key' => '',
'Default' => NULL,
'Extra' => '',
'php' => 'string',
],
'forename' => [
'Field' => 'forename',
'Type' => 'varchar(25)',
'Null' => 'NO',
'Key' => '',
'Default' => NULL,
'Extra' => '',
'php' => 'string',
],
'lastname' => [
'Field' => 'lastname',
'Type' => 'varchar(25)',
'Null' => 'NO',
'Key' => '',
'Default' => NULL,
'Extra' => '',
'php' => 'string',
],
]
$oPDO query를 사용하는 SQL 예 .. Fetch
/**
* @return FooDataTypeDTFooModelTableUser
* @throws ReflectionException
*/
public function getUserObject ()
{
// get result & cast to datatype object
$ oDTFooModelTableUser = DTFooModelTableUser:: create (
( array ) DB :: $ oPDO
-> query ( " SELECT * FROM `FooModelTableUser` WHERE `id` = '1' " )
-> fetch ( PDO :: FETCH_ASSOC )
);
return $ oDTFooModelTableUser
} // type: object
FooDataTypeDTFooModelTableUser::__set_state(array(
'id' => 1,
'stampChange' => '2023-09-28 10:18:03',
'stampCreate' => '2023-09-28 10:16:14',
'id_TableGroup' => 1,
'email' => '[email protected]',
'active' => 1,
'uuid' => '8b838038-5dd7-11ee-8620-2cf05d0841fd',
'uuidtmp' => '8b838839-5dd7-11ee-8620-2cf05d0841fd',
'password' => '*******************************************',
'nickname' => 'admin',
'forename' => 'foo',
'lastname' => 'bar',
))
$oPDO query를 사용하는 SQL 예 .. Fetchall
/**
* @return array|FooDataTypeDTFooModelTableUser[]
* @throws ReflectionException
*/
public function getUserObjectsArray ()
{
// get result & cast all results to datatype objects
$ aDTFooModelTableUser = array_map (
function ( $ aData ){
return DTFooModelTableUser:: create ( $ aData );
},
( array ) DB :: $ oPDO
-> query ( " SELECT * FROM `FooModelTableUser` WHERE `active` = '1' " )
-> fetchAll ( PDO :: FETCH_ASSOC )
);
return $ aDTFooModelTableUser
} // type: array, items: 2
[
0 => [
FooDataTypeDTFooModelTableUser::__set_state(array(
'id' => 1,
'stampChange' => '2023-09-28 10:18:03',
'stampCreate' => '2023-09-28 10:16:14',
'id_TableGroup' => 1,
'email' => '[email protected]',
'active' => 1,
'uuid' => '8b838038-5dd7-11ee-8620-2cf05d0841fd',
'uuidtmp' => '8b838839-5dd7-11ee-8620-2cf05d0841fd',
'password' => '*******************************************',
'nickname' => 'admin',
'forename' => 'foo',
'lastname' => 'bar',
)],
1 => [
FooDataTypeDTFooModelTableUser::__set_state(array(
'id' => 2,
'stampChange' => '2023-09-28 10:18:03',
'stampCreate' => '2023-09-28 10:16:14',
'id_TableGroup' => 1,
'email' => '[email protected]',
'active' => 1,
'uuid' => '1b838038-5dd7-11ee-8620-2cf05d0841fd',
'uuidtmp' => '2b838839-5dd7-11ee-8620-2cf05d0841fd',
'password' => '*******************************************',
'nickname' => 'foo',
'forename' => 'foo2',
'lastname' => 'bar2',
)],
]
db.model.db.construct.saveCache
db.model.db.setSqlLoggingState.exception
db.model.db.setForeignKey.exception
db.model.db.checkIfTableExists.exception
db.model.db.createTable.exception
db.model.db.synchronizeFields.exception
db.model.db.synchronizeFields.delete.exception
db.model.db.synchronizeFields.insert.exception
db.model.db.synchronizeFields.update.exception
db.model.db.create.sql
db.model.db.createTable.sql
db.model.db.insert.sql
db.model.db.create.exception
db.model.db.retrieve.sql
db.model.db.retrieve.exception
db.model.db.count.sql
db.model.db.count.exception
db.model.db.update.sql
db.model.db.update.exception
db.model.db.delete.sql
db.model.db.delete.exception
이벤트를 들으면 SQL 쿼리를 기록 할 수 있습니다.
MyMVC 모듈의 이벤트 폴더에서 파일 sql.php 작성하고 다음과 같이 바인딩을 선언하십시오.
/modules/{MODULE}/etc/event/sql.php
#-------------------------------------------------------------
# declare bindings
$ aEvent = [
' db.model.db.create.sql ' => array (
function ( MVC DataType DTArrayObject $ oDTArrayObject ) {
MVC Log:: write ( $ oDTArrayObject -> getDTKeyValueByKey ( ' sSql ' )-> get_sValue (), ' sql.log ' );
}
),
' db.model.db.insert.sql ' => array (
function ( MVC DataType DTArrayObject $ oDTArrayObject ) {
MVC Log:: write ( $ oDTArrayObject -> getDTKeyValueByKey ( ' sSql ' )-> get_sValue (), ' sql.log ' );
}
),
' db.model.db.retrieve.sql ' => array (
function ( MVC DataType DTArrayObject $ oDTArrayObject ) {
MVC Log:: write ( $ oDTArrayObject -> getDTKeyValueByKey ( ' sSql ' )-> get_sValue (), ' sql.log ' );
}
),
' db.model.db.update.sql ' => array (
function ( MVC DataType DTArrayObject $ oDTArrayObject ) {
MVC Log:: write ( $ oDTArrayObject -> getDTKeyValueByKey ( ' sSql ' )-> get_sValue (), ' sql.log ' );
}
),
' db.model.db.delete.sql ' => array (
function ( MVC DataType DTArrayObject $ oDTArrayObject ) {
MVC Log:: write ( $ oDTArrayObject -> getDTKeyValueByKey ( ' sSql ' )-> get_sValue (), ' sql.log ' );
}
),
' db.model.db.createTable.sql ' => array (
function ( MVC DataType DTArrayObject $ oDTArrayObject ) {
MVC Log:: write ( $ oDTArrayObject -> getDTKeyValueByKey ( ' sSql ' )-> get_sValue (), ' sql.log ' );
}
),
];
#-------------------------------------------------------------
# process: bind the declared ones
MVC Event:: processBindConfigStack ( $ aEvent );