PDOONE。これは、SQL Server(2008 R2以上)、MySQL(5.7以降)、Oracle(12.1以降)と互換性があるPHPのPDOライブラリのシンプルなラッパーです。
このライブラリは、できるだけ早く動作しようとします。ほとんどの操作は、単純な文字列/配列管理であり、PDOライブラリの裸の金属で動作しますが、拡張EFTEC/PDOONEOMを使用してORMを作成することもできます。
これを回します
$ stmt = $ pdo -> prepare ( " SELECT * FROM myTable WHERE name = ? " );
$ stmt -> bindParam ( 1 , $ _POST [ ' name ' ], PDO :: PARAM_STR );
$ stmt -> execute ();
$ result = $ stmt -> get_result ();
$ products =[];
while ( $ row = $ result -> fetch_assoc ()) {
$ product []= $ row ;
}
$ stmt -> close ();これに
$ products = $ pdoOne
-> select ( " * " )
-> from ( " myTable " )
-> where ( " name = ? " ,[ $ _POST [ ' name ' ]])
-> toList ();またはORMの使用(EFTEC/PDOONEOMライブラリを使用)
ProductRepo // this class was generated with echo $pdoOne()->generateCodeClass(['Product']); or using the cli.
:: where ( " name = ? " ,[ $ _POST [ ' name ' ]])
:: toList ();| ExampleTicketPhp | カップケーキの例 | 検索の例 | 別の方法の例 |
|---|---|---|---|
![]() | ![]() | ![]() |
その他の例:
PDOONEを使用したMySQL PHPおよびPDOの例
このライブラリにはPHP 7.1以上が必要であり、拡張PDOと拡張PDO-MysQl(MySQL)、PDO-SQLSRV(SQL Server)またはPDO-OCI(Oracle)が必要です。
composer.json次の要件を編集してから、Composerを更新します。
{
"require" : {
"eftec/PdoOne" : " ^4.0.1 "
}
}または、CLIを使用してインストールします
作曲家にはEFTEC/PDOONEが必要です
フォルダLIBをライブラリからダウンロードして、フォルダープロジェクトに入れてください。次に、それに含まれるすべてのファイルを含める必要があります。
次のように、クラスPDOONEのインスタンスを作成します。次に、Method Connect()またはOpen()を使用して接続を開くことができます
use eftec PdoOne ;
// mysql
$ dao = new PdoOne ( " mysql " , " 127.0.0.1 " , " root " , " abc.123 " , " sakila " , "" );
$ conn -> logLevel = 3 ; // it is for debug purpose and it works to find problems.
$ dao -> connect ();
// sql server 10.0.0.1instance or (local)instance or machinenameinstance or machine (default instance)
$ dao = new PdoOne ( " sqlsrv " , " (local)sqlexpress " , " sa " , " abc.123 " , " sakila " , "" );
$ conn -> logLevel = 3 ; // it is for debug purpose and it works to find problems.
$ dao -> connect ();
// test (mockup)
$ dao = new PdoOne ( " test " , " anyy " , " any " , " any " , " any " , "" );
$ dao -> connect ();
// oci (oracle) ez-connect. Remember that you must have installed Oracle Instant client and added to the path.
$ cs = ' (DESCRIPTION =(ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))(CONNECT_DATA =(SERVER = DEDICATED)(SERVICE_NAME = instancia1))) ' ;
$ dao = new PdoOne ( " oci " , $ cs , " sa " , " abc.123 " ); // oracle uses the user as the schema
$ conn -> logLevel = 3 ; // it is for debug purpose and it works to find problems.
$ dao -> connect ();
// oci (oracle) tsnnames (the environment variables TNS_ADMIN and PATH must be correctly configured), also tnsnames.ora must exists.
$ cs = ' instancia1 ' ;
$ dao = new PdoOne ( " oci " , $ cs , " sa " , " abc.123 " ); // oracle uses the user as the schema
$ conn -> logLevel = 3 ; // it is for debug purpose and it works to find problems.
$ dao -> connect ();どこ
$ dao = new pdoone( "mysql"、 "127.0.0.1"、 "root"、 "abc.123"、 "sakila"、 "");
Oracleはインストールが難しいです。 Windowsでは、Oracle HomeのBinフォルダーから、すべてのDLLをPHPフォルダーとApacheフォルダーにコピーする必要があります。
Method runrawquery()を使用すると、パラメーターの有無にかかわらずコマンドをPDOに直接実行できます。また、 pdostatementまたは配列を返す可能性があります。スピードが必要なときに便利です。
runrawquery($ rawsql、$ param、$ returnarray、$ fetchmode、$ fetchargument)
string $ rawsqlアレイを実行するクエリ| null $ param [type1、value1、type2、value2]または[name1 => value、name2 = value2] bool $ returnArray true(default)から配列を返します。 falseの場合、 pdostatement int $ $ fetchmodeを返すと、フェッチするモードが表示されます。例:PDO :: FETCH_ASSOC NULL $ fetchModeの引数。
$ sql = ' select * from table where id=1 ' ;
$ pdoStatement = $ pdoOne -> runRawQuery ( $ sql ,[], false ); // [] are the parametersただし、配列を返すように変更できます
$ sql = ' select * from table where id=1 ' ;
$ values = $ pdoOne -> runRawQuery ( $ sql ); // [] are the parametersパラメーターを渡すこともできます。
$ values = $ con -> runRawQuery ( ' select * from table where id=? ' ,[ 20 ]); // with parameter
$ values = $ con -> runRawQuery ( ' select * from table where id=:name ' ,[ ' name ' => 20 ]); // with named parameter
$ values = $ con -> runRawQuery ( ' select * from table ' ,[]); // without parameter.注意してください、このライブラリは準備されたステートメントを使用しているため、SQL注入がありません(パラメーターを使用する場合)
$ name = " O'hara " ;
$ values = $ con -> runRawQuery ( " select * from table where name=:name " ,[ ' name ' => $ name ]); // it works.✅
$ values = $ con -> runRawQuery ( " select * from table where name=? " ,[ $ name ]); // it works ok.✅
$ values = $ con -> runRawQuery ( " select * from table where name=' $ name ' " ); // it will crash.メソッドrunquery()を使用すると、PDOで作成されたステートメントを実行できます。引数を渡したいときに役立ちます。 runquery()にはPDO準備が必要です。
この方法は、PDOステートメントを既に操作していない限り、推奨されません。すべてのコードを適応させたくありません。
$ sql = " insert into `product`(name) values(?) " ;
$ stmt = $ pdoOne -> prepare ( $ sql );
$ productName = " Cocacola " ;
$ stmt -> bind_param ( " s " , $ productName ); // s stand for a string. Also i =integer, d = double and b=blob
$ rows = $ pdoOne -> runQuery ( $ stmt );
$ allRows = $ rows -> fetch_all ( PDO :: FETCH_ASSOC );クエリビルダーを使用してコマンドを作成できます。詳細については、クエリビルダー(DQL)に関する章を確認できます。
// query builder
$ pdoOne -> set ([ ' name ' => ' cocacola ' ])
-> from ( ' product ' )
-> insert ();ライブラリEFTEC PDOONEOMを使用すると、テーブルの[ORM] (#ORM)を作成できます。 ORMを生成した場合は、次のコードを使用できます
ProductRepo:: toList ([ ' category ' => ' drink ' ]);ここで、 ProductrepoはORMを使用して生成されるサービスクラスです。
デフォルトでは、PDOONEはモードPDO :: FETCH_ASSOCでクエリを実行します。クエリを実行することで変更できます。
$ pdo -> setFechMode ( PDO :: FETCH_CLASS , ' stdClass ' )-> runRawQuery ( $ query );
// or you can run as
$ pdo -> runRawQuery ( $ query , null , true , false , null , PDO :: FETCH_CLASS , ' stdClass ' )PDOONEでは、5種類の日付を許可します。
SQL形式は、日付がデータベースに保存される方法です。データベースのタイプに依存します。たとえば、MySQLはフォーマットYMDを使用できます。
人間形式それは、エンドユーザーが私たちの日付をどのように見えるかの形式です。
ISO日付形式。これは、値をどのように輸送し、シリアル化することができるかという形式です。
タイムスタンプ:1970年1月1日以降の秒数がカウントされます
クラス / PHPクラス:それはDateTimeオブジェクトです。
トランザクションを実行する3つの方法があります。
| 方法 | 説明 |
|---|---|
| StartTransaction() | トランザクションを開始します。タイプデータベースに応じて、積み重ねられるかどうか。 |
| 専念() | トランザクションをコミット(および閉じる) |
| rollback() | トランザクションをロールバック(および閉じる) |
例:
try {
$ sql = " insert into `product`(name) values(?) " ;
$ pdoOne -> startTransaction ();
$ result = $ pdoOne -> runRawQuery ( $ sql ,[ ' Fanta ' => $ productName ], false );
$ pdoOne -> commit (); // transaction ok
} catch ( Exception $ e ) {
$ pdoOne -> rollback ( false ); // error, transaction cancelled, the false means that it doesn't throw an exception if we want rollback.
}テーブルが存在する場合はtrueを返します(現在のデータベース/スキーマ)
テーブルの列の統計(配列として)を返します。
$ stats = $ pdoOne -> statValue ( ' actor ' , ' actor_id ' );| 分 | マックス | 平均 | 和 | カウント |
|---|---|---|---|---|
| 1 | 205 | 103.0000 | 21115 | 205 |
テーブルのすべての列を返します
$ result = $ pdoOne -> columnTable ( ' actor ' );| colname | coltype | colsize | コルプレス | コルスケール | ISKEY | Isidentity |
|---|---|---|---|---|---|---|
| actor_id | Smallint | 5 | 0 | 1 | 1 | |
| ファーストネーム | varchar | 45 | 0 | 0 | ||
| 苗字 | varchar | 45 | 0 | 0 | ||
| last_update | タイムスタンプ | 0 | 0 |
テーブルのすべての外部キーを返します(ソーステーブル)
定義と主キーを使用してテーブルを作成します。
注:CLI(出力クラスコード)を実行して、既存のテーブルを使用してテーブルを作成するコードを生成できます。
PHP PDOONE.PHP -DATABASE MYSQL -SERVER 127.0.0.1 -USER ROOT -PWD ABC.123 -DB SAKILA -INPUT FILM -OUTPUT CLASSCODE
例:( mysql)
$ pdo -> createTable ( ' film ' ,
[
" film_id " => " smallint unsigned not null auto_increment " ,
" title " => " varchar(255) not null " ,
" description " => " text " ,
" release_year " => " year " ,
" language_id " => " tinyint unsigned not null " ,
" original_language_id " => " tinyint unsigned " ,
" rental_duration " => " tinyint unsigned not null default '3' " ,
" rental_rate " => " decimal(4,2) not null default '4.99' " ,
" length " => " smallint unsigned " ,
" replacement_cost " => " decimal(5,2) not null default '19.99' " ,
" rating " => " enum('G','PG','PG-13','R','NC-17') default 'G' " ,
" special_features " => " set('Trailers','Commentaries','Deleted Scenes','Behind the Scenes') " ,
" last_update " => " timestamp not null default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP "
],[
" film_id " => " PRIMARY KEY " ,
" title " => " KEY " ,
" language_id " => " FOREIGN KEY REFERENCES`language`(`language_id`) ON UPDATE CASCADE " ,
" original_language_id " => " FOREIGN KEY REFERENCES`language`(`language_id`) ON UPDATE CASCADE "
]); $ pdo -> createTable ( ' film ' ,
[
" film_id " => " smallint unsigned not null auto_increment " ,
" title " => " varchar(255) not null " ,
" description " => " text " ,
" release_year " => " year " ,
" language_id " => " tinyint unsigned not null " ,
" original_language_id " => " tinyint unsigned " ,
" rental_duration " => " tinyint unsigned not null default '3' " ,
" rental_rate " => " decimal(4,2) not null default '4.99' " ,
" length " => " smallint unsigned " ,
" replacement_cost " => " decimal(5,2) not null default '19.99' " ,
" rating " => " enum('G','PG','PG-13','R','NC-17') default 'G' " ,
" special_features " => " set('Trailers','Commentaries','Deleted Scenes','Behind the Scenes') " ,
" last_update " => " timestamp not null default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP "
], ' film_id ' ); 例(SQLSRV)
$ pdo -> createTable ( ' film ' ,
[
" film_id " => " int NOT NULL IDENTITY(1,1) " ,
" title " => " varchar(255) NOT NULL " ,
" description " => " text(2147483647) DEFAULT (NULL) " ,
" release_year " => " varchar(4) " ,
" language_id " => " tinyint NOT NULL " ,
" original_language_id " => " tinyint DEFAULT (NULL) " ,
" rental_duration " => " tinyint NOT NULL DEFAULT ((3)) " ,
" rental_rate " => " decimal(4,2) NOT NULL DEFAULT ((4.99)) " ,
" length " => " smallint DEFAULT (NULL) " ,
" replacement_cost " => " decimal(5,2) NOT NULL DEFAULT ((19.99)) " ,
" rating " => " varchar(10) DEFAULT ('G') " ,
" special_features " => " varchar(255) DEFAULT (NULL) " ,
" last_update " => " datetime NOT NULL DEFAULT (getdate()) "
],[
" language_id " => " FOREIGN KEY REFERENCES language(language_id) " ,
" original_language_id " => " FOREIGN KEY REFERENCES language(language_id) " ,
" film_id " => " PRIMARY KEY "
]);依存関係によって順序付けられたテーブルのリストを返します(依存からより依存するまで)
注:テーブルには円形の参照がある可能性があるため、この操作は完全に操作できません。
$ dao = new PdoOne ( ' sqlsrv ' , " (local)sqlexpress " , " sa " , " abc.123 " , " sakila " );
$ dao -> open ();
echo " <pre> " ;
var_dump ( $ dao -> tableSorted ( 3 , false , true )); // it returns the tables sortered
var_dump ( $ dao -> tableSorted ( 3 , true , true )); // it returns all the tables that can't be sortered
echo " </pre> " ;テーブルが値でasignした定義と一致する場合、テーブルを検証します。
$def=[
"film_id" => "int NOT NULL IDENTITY(1,1)",
"title" => "varchar(255) NOT NULL",
"description" => "text(2147483647) DEFAULT (NULL)",
"release_year" => "varchar(4)",
"language_id" => "tinyint NOT NULL",
"original_language_id" => "tinyint DEFAULT (NULL)",
"rental_duration" => "tinyint NOT NULL DEFAULT ((3))",
"rental_rate" => "decimal(4,2) NOT NULL DEFAULT ((4.99))",
"length" => "smallint DEFAULT (NULL)",
"replacement_cost" => "decimal(5,2) NOT NULL DEFAULT ((19.99))",
"rating" => "varchar(10) DEFAULT ('G')",
"special_features" => "varchar(255) DEFAULT (NULL)",
"last_update" => "datetime NOT NULL DEFAULT (getdate())"
];
$keys=[
"language_id" => "FOREIGN KEY REFERENCES language(language_id)",
"original_language_id" => "FOREIGN KEY REFERENCES language(language_id)",
"film_id" => "PRIMARY KEY"
];
var_dump(PdoOne::validateDefTable(self::getPdoOne(),self::TABLE,$def,$keys));
テーブルのすべての外国の鍵を返します。
$ result = $ pdoOne -> foreignKeyTable ( ' actor ' );| コロカル | tableRem | コルム |
|---|---|---|
| customer_id | お客様 | customer_id |
| Rental_id | レンタル | Rental_id |
| staff_id | スタッフ | staff_id |
また、手続き上のクエリを作成することもできます。
例:
$ results = $ pdoOne -> select ( " * " )-> from ( " producttype " )
-> where ( ' name=? ' , [ ' Cocacola ' ])
-> where ( ' idproducttype=? ' , [ 1 ])
-> toList (); 返す列を示します。引数はSQLコマンドであるため、関数、定数、演算子、エイリアスなどのデータベースサポートが操作を許可します。
$ results = $ pdoOne -> select ( " col1,col2 " ); //...クエリを生成します: col1、col2を選択してください。
$ results = $ pdoOne -> select ( " select * from table " ); //->...クエリを生成します: [テーブル]から[ *]を選択します。
値のカウントを返すクエリを生成します。それはメソッドselect()のマクロです
$ result = $ pdoOne -> count ( ' from table where condition=1 ' ); // select count(*) from table where c..
$ result = $ pdoOne -> count ()-> from ( ' table ' )-> where ( ' condition=? ' ,[ 1 ]); // select count(*) from table where c..
$ result = $ pdoOne -> count ( ' from table ' , ' col1 ' ); // select count(col1) from table
$ result = $ pdoOne -> count ()-> from ( ' table ' ); // select count(*) from table列の最小値を返すクエリを生成します。 $ argが空の場合、列の名前に$ sqlを使用します。これはメソッドselect()のマクロです
$ result = $ pdoOne -> min ( ' from table where condition=1 ' , ' col ' ); // select min(col) from table where c..
$ result = $ pdoOne -> min ( ' from table ' , ' col1 ' ); // select min(col1) from table
$ result = $ pdoOne -> min ( '' , ' col1 ' )-> from ( ' table ' ); // select min(col1) from table
$ result = $ pdoOne -> min ( ' col1 ' )-> from ( ' table ' ); // select min(col1) from table列の最大値を返すクエリを生成します。 $ argが空の場合、列の名前に$ sqlを使用します。これはメソッドselect()のマクロです
$ result = $ pdoOne -> max ( ' from table where condition=1 ' , ' col ' ); // select max(col) from table where c..
$ result = $ pdoOne -> max ( ' from table ' , ' col1 ' ); // select max(col1) from table列の合計値を返すクエリを生成します。 $ argが空の場合、列の名前に$ sqlを使用します。これはメソッドselect()のマクロです
$ result = $ pdoOne -> sum ( ' from table where condition=1 ' , ' col ' ); // select sum(col) from table where c..
$ result = $ pdoOne -> sum ( ' from table ' , ' col1 ' ); // select sum(col1) from table列の平均値を返すクエリを生成します。 $ argが空の場合、列の名前に$ sqlを使用します。これはメソッドselect()のマクロです
$ result = $ pdoOne -> avg ( ' from table where condition=1 ' , ' col ' ); // select avg(col) from table where c..
$ result = $ pdoOne -> avg ( ' from table ' , ' col1 ' ); // select avg(col1) from table選択コマンドを生成します。
$ results = $ pdoOne -> select ( " col1,col2 " )-> distinct (); //...クエリを生成します:異なるcol1、col2を選択してください。
注:>個別( 'ユニーク')returns select selectユニーク..
「from」SQLコマンドを生成します。
$ results = $ pdoOne -> select ( " * " )-> from ( ' table ' ); //...クエリを生成します: [テーブル]から[ *]を選択します
$テーブルは、単一のテーブルまたはSQL構造です。 Exampの場合、次のコマンドは有効です。
$ results = $ pdoOne -> select ( " * " )-> from ( ' table t1 inner join t2 on t1.c1=t2.c2 ' ); //...WHEREコマンドを生成します。
$ results = $ pdoOne -> select ( " * " )
-> from ( ' table ' )
-> where ( ' p1=1 ' ); //...どこに異なる方法で表現できます。
次のように、パラメーターなしでWhereを書くことが可能です。
$ results = $ pdoOne -> select ( " * " )-> from ( ' table ' )-> where ( " p1=1 and p2>2.5 or p3 like '%aa%' " ); $ aa = ' aa ' ;
$ results = $ pdoOne -> select ( " * " )-> from ( ' table ' )-> where ( " p1=? and p2>? or p3 like ? " ,[ 1
, 2.5
, " % $ aa % " ]);それも機能します
// (if there is only a single argument without a type)
$ results = $ pdoOne -> select ( " * " )-> from ( ' table ' )-> where ( " p1=? " ,[ 1 ]); // = where("p1=?",[1]);
// (if we don't define to where to put the value)
$ results = $ pdoOne -> select ( " * " )-> from ( ' table ' )-> where ( " p1 " ,[ 1 ]); // = where("p1=?",[1]); これは、関連配列を使用したクエリの速記の定義であり、キーは列の名前であり、値は比較する値です
それは平等(=)とロジック演算子'と'でのみ動作します(タイプは自動的に定義されます)
// select * from table where p1='1' and p2='2.5' and p3='aa'
$ results = $ pdoOne -> select ( " * " )-> from ( ' table ' )-> where ([ ' p1 ' => 1
, ' p2 ' => 2.5
, ' p3 ' => ' aa ' ]); また、パラメーターのタイプを指定することも可能です。
// select * from table where p1=1 and p2='2.5' and p3='aa'
$ results = $ pdoOne -> select ( " * " )-> from ( ' table ' )-> where ([ ' p1 ' =>[ 1 ]
, ' p2 ' =>[ 2.5 ]
, ' p3 ' =>[ ' aa ' ]]); また、連想配列を引数として使用し、クエリの名前付きパラメーターを使用することもできます
$ results = $ pdoOne -> select ( " * " )-> from ( " table " )
-> where ( ' condition=:p1 and condition2=:p2 ' ,[ ' p1 ' => ' Coca-Cola ' , ' p2 ' => 1 ])
-> toList ();クエリを生成します:select * from tableここでcondition =?(coca-cola)およびcondition2 =?(1)
クエリを生成します:[P1 = 1]から[テーブルから]を選択します
注:ArrayParametersは次のように配列です:タイプ、値。
ここで、タイプはi = integer、d = double、s = stringまたはb = blobです。疑わしい場合は、「S」を使用してください(テーブルの順位を参照)
ArrayParametersの例:
[1、 'Hello'、20.3、 'world']
$ results = $ pdoOne -> select ( " * " )
-> from ( ' table ' )
-> where ( ' p1=? ' ,[ 1 ]); //...クエリを生成します: [p1 =?(1)]テーブルから * select *
$ results = $ pdoOne -> select ( " * " )
-> from ( ' table ' )
-> where ( ' p1=? and p2=? ' ,[ 1 , ' hello ' ]); //...クエリを生成: [p1 =?(1)およびp2 =?( 'hello')を選択する[テーブル]を選択します
注記。どこにネストできますか。
$ results = $ pdoOne -> select ( " * " )
-> from ( ' table ' )
-> where ( ' p1=? ' ,[ 1 ])
-> where ( ' p2=? ' ,[ ' hello ' ]); //...クエリを生成: [p1 =?(1)およびp2 =?( 'hello')を選択する[テーブル]を選択します
使用することもできます。
$ results = $ pdoOne -> select ( " * " )-> from ( " table " )
-> where ([ ' p1 ' => ' Coca-Cola ' , ' p2 ' => 1 ])
-> toList ();クエリを生成します:select * from p1 =?(coca-cola)およびp2 =?(1)
注文コマンドを生成します。
$ results = $ pdoOne -> select ( " * " )
-> from ( ' table ' )
-> order ( ' p1 desc ' ); //...クエリを生成します: p1 descでテーブルオーダーから * select *
グループコマンドを生成します。
$ results = $ pdoOne -> select ( " * " )
-> from ( ' table ' )
-> group ( ' p1 ' ); //...クエリを生成します: p1によってテーブルグループから * select *
コマンドを生成します。
注: where()と同じパラメーターを使用します
$ results = $ pdoOne -> select ( " * " )
-> from ( ' table ' )
-> group ( ' p1 ' )
-> having ( ' p1>? ' , array ( 1 )); //...クエリを生成します:p1>?(1)を持つp1によってテーブルグループから * select * from tableグループ
注:ネストされている可能性があります() - > having()
注:パラメーターがない可能性があります( 'col> 10')
クエリ生成を実行します。
注ReturnArrayがtrueの場合、連想配列を返します。 returnArrayがfalseの場合、mysqli_resultを返します
注:現在のパラメーター(現在の選択、from、場所など)をリセットします。
Rungen()のマクロです。操作が失敗した場合、連想配列またはfalseを返します。
$ results = $ pdoOne -> select ( " * " )
-> from ( ' table ' )
-> toList (); 現在のクエリからpdostatementを返します
注:ステートメントをループしたい場合は、fetchloop()を使用できます。
例:
$ stmt = $ pdoOne -> select ( " * " )
-> from ( ' table ' )
-> toPdoStatement ();
while ( $ row = $ stmt -> fetch ()) {
// do something
}すべての行のクエリを取得します。
この方法は、すべての情報を一度に読みたくないときに使用できます。そのため、各行を個別に読み取り、処理できます
例:
$ this -> select ( ' select id,name from table ' )
-> fetchLoop ( static function ( $ row ) { return ( $ row );}, PDO :: FETCH_ASSOC )クエリの各列のメタコード(定義)を返します。
$ results = $ pdoOne -> select ( " * " )
-> from ( ' table ' )
-> toMeta (); または
$ results = $ pdoOne -> toMeta ( ' select * from table ' ); 結果:
array(3) {
[0]=>
array(7) {
["native_type"]=>
string(4) "LONG"
["pdo_type"]=>
int(2)
["flags"]=>
array(2) {
[0]=>
string(8) "not_null"
[1]=>
string(11) "primary_key"
}
["table"]=>
string(11) "producttype"
["name"]=>
string(13) "idproducttype"
["len"]=>
int(11)
["precision"]=>
int(0)
}
[1]=>
array(7) {
["native_type"]=>
string(10) "VAR_STRING"
["pdo_type"]=>
int(2)
["flags"]=>
array(0) {
}
["table"]=>
string(11) "producttype"
["name"]=>
string(4) "name"
["len"]=>
int(135)
["precision"]=>
int(0)
}
}
Rungenのマクロです。最初の列からインデックス付き配列を返します
$ results = $ pdoOne -> select ( " * " )
-> from ( ' table ' )
-> toListSimple (); // ['1','2','3','4'] 最初の値がキーであり、2番目の値が値である連想配列を返します。
2番目の値が存在しない場合、インデックスを値として使用します(最初の値)。
$ results = $ pdoOne -> select ( " cod,name " )
-> from ( ' table ' )
-> toListKeyValue (); // ['cod1'=>'name1','cod2'=>'name2'] Rungenのマクロです。 mysqli_resultまたはnullを返します。
$ results = $ pdoOne -> select ( " * " )
-> from ( ' table ' )
-> toResult (); // クエリの最初のスカラー(1つの値)を返します。 $ colnameの場合、最初の列を使用します。
$ count = $ this -> count ( ' from product_category ' )-> firstScalar ();Rungenのマクロです。存在しない場合は、最初の行を連想配列として返します。
$ results = $ pdoOne -> select ( " * " )
-> from ( ' table ' )
-> first (); Rungenのマクロです。連想配列として最後の行(もしあれば、falseを返します)を返します。
$ results = $ pdoOne -> select ( " * " )
-> from ( ' table ' )
-> last (); last()がすべての値を読み取るため、Order()およびFirst()を実行する方が効率的である場合があります。
SQLコマンドと文字列を返します。
$ sql = $ pdoOne -> select ( " * " )
-> from ( ' table ' )
-> sqlGen ();
echo $ sql ; // returns select * from table
$ results = $ pdoOne -> toList (); // executes the query注:クエリをリセットしません。
各コマンドを実行する4つの方法があります。
値20の列col1に整数を追加したいとしましょう。
値のリストを使用したスキーマと値:最初の値が列である場合、2番目は値のタイプ(i = integer、d = double、s = string、b = blob)で、2番目の配列に値が含まれます。
$ pdoOne -> insert ( " table "
,[ ' col1 ' ]
,[ 20 ]);同じリストのスキーマと値:最初の値が列である場合、2番目は値のタイプ(i = integer、d = double、s = string、b = blob)、3番目は値です。
$ pdoOne -> insert ( " table "
,[ ' col1 ' , 20 ]);2つの連想配列を使用したスキーマと値:
$ pdoOne -> insert ( " table "
,[ ' col1 ' ]
,[ ' col1 ' => 20 ]);単一の連想配列を使用したスキーマと値:タイプは自動的に計算されます。
$ pdoOne -> insert ( " table "
,[ ' col1 ' => 20 ]);挿入コマンドを生成します。
$ pdoOne -> insert ( " producttype "
,[ ' idproducttype ' , ' name ' , ' type ' ]
,[ 1 , ' cocacola ' , 1 ]);ネストされたチェーンの使用(シングルアレイ)
$ pdoOne -> from ( " producttype " )
-> set ([ ' idproducttype ' , 0 , ' name ' , ' Pepsi ' , ' type ' , 1 ])
-> insert ();ネストされたチェーンマルチセットを使用します
$ pdoOne -> from ( " producttype " )
-> set ( " idproducttype=? " ,[ 101 ])
-> set ( ' name=? ' ,[ ' Pepsi ' ])
-> set ( ' type=? ' ,[ 1 ])
-> insert ();または(タイプは、可能な限り、mysqlによって自動的に定義されます)
$ pdoOne -> from ( " producttype " )
-> set ( " idproducttype=? " ,[ 101 ])
-> set ( ' name=? ' , ' Pepsi ' )
-> set ( ' type=? ' , 1 )
-> insert (); $ pdoOne -> insertObject ( ' table ' ,[ ' Id ' => 1 , ' Name ' => ' CocaCola ' ]);ネストされたチェーン宣言セットを使用します
$ pdoOne -> from ( " producttype " )
-> set ( ' (idproducttype,name,type) values (?,?,?) ' ,[ 100 , ' Pepsi ' , 1 ])
-> insert ();クエリを生成します:inserting productype(idproducttype、name、type)values(?、?、?) ....
挿入コマンドを生成します。
$ pdoOne -> update ( " producttype "
,[ ' name ' , ' type ' ] //set
,[ 6 , ' Captain-Crunch ' , 2 ] //set
,[ ' idproducttype ' ] // where
,[ 6 ]); // where $ pdoOne -> update ( " producttype "
,[ ' name ' => ' Captain-Crunch ' , ' type ' => 2 ] // set
,[ ' idproducttype ' => 6 ]); // where $ pdoOne -> from ( " producttype " )
-> set ( " name=? " ,[ ' Captain-Crunch ' ]) //set
-> set ( " type=? " ,[ 6 ]) //set
-> where ( ' idproducttype=? ' ,[ 6 ]) // where
-> update (); // updateまたは
$ pdoOne -> from ( " producttype " )
-> set ( " name=? " , ' Captain-Crunch ' ) //set
-> set ( " type=? " , 6 ) //set
-> where ( ' idproducttype=? ' ,[ 6 ]) // where
-> update (); // updateクエリを生成します: update productType set
name=?、type=?どこでidproducttype=? ...
削除コマンドを生成します。
$ pdoOne -> delete ( " producttype "
,[ ' idproducttype ' ] // where
,[ 7 ]); // where $ pdoOne -> delete ( " producttype "
,[ ' idproducttype ' => 7 ]); // whereクエリを生成します: delete from productType where
idproducttype=? ...
DQLビルダーチェーンを介して削除することもできます。
$ pdoOne -> from ( " producttype " )
-> where ( ' idproducttype=? ' ,[ 7 ]) // where
-> delete (); $ pdoOne -> from ( " producttype " )
-> where ([ ' idproducttype ' => 7 ]) // where
-> delete (); クエリを生成します: delete from productType where
idproducttype=? ...
オプションでクエリの結果をキャッシュすることができます。クエリの期間もクエリで定義されています。クエリの結果がキャッシュされていない場合は、正常に計算されます(データベースのクエリを実行します)。クエリを一意として識別するために、システムは、クエリ、パラメーター、メソッド、および操作の種類で作成されたSHA256に基づいて一意のID(UID)を生成します。
ライブラリは直接キャッシュ操作を行いません。代わりに、外部ライブラリを使用して結果をキャッシュできます。
class CacheService implements eftec IPdoOneCache {
public $ cacheData =[];
public $ cacheCounter = 0 ; // for debug
public function getCache ( $ uid , $ family = '' ) {
if ( isset ( $ this -> cacheData [ $ uid ])) {
$ this -> cacheCounter ++;
echo " using cache n" ;
return $ this -> cacheData [ $ uid ];
}
return false ;
}
public function setCache ( $ uid , $ family = '' , $ data = null , $ ttl = null ) {
$ this -> cacheData [ $ uid ]= $ data ;
}
public function invalidateCache ( $ uid = '' , $ family = '' ) {
unset( $ this -> cacheData [ $ uid ]);
}
}
$ cache = new CacheService ();(2)キャッシュサービスを設定します
$ pdoOne = new PdoOne ( " mysql " , " 127.0.0.1 " , " travis " , "" , " travisdb " );
$ cache = new CacheService ();
$ $ pdoOne -> setCacheService ( $ cache );(3)キャッシュを次のように使用するには、クエリの任意の部分にusecache()メソッドを追加する必要があります。
$ pdoOne -> select ( ' select * from table ' )
-> useCache ()-> toList (); // cache that never expires
$ pdoOne -> select ( ' select * from table ' )
-> useCache ( 1000 )-> toList (); // cache that lasts 1000ms. class CacheService implements eftec IPdoOneCache {
public function getCache ( $ uid , $ family = '' ) {
return apcu_fetch ( $ uid );
}
public function setCache ( $ uid , $ family = '' , $ data = null , $ ttl = null ) {
apcu_store ( $ uid , $ data , $ ttl );
}
public function invalidateCache ( $ uid = '' , $ family = '' ) {
// invalidate cache
apcu_delete ( $ uid );
}
}
$ cache = new CacheService ();シーケンスは、Auto_Numeric(ID)フィールドに代わるものです。シーケンスを作成する2つの方法があります:スノーフレークとシーケンス。これは、主に数字を返すため、GUIDを作成するための代替手段です(ガイドは通常、インデックスと保存するのがより高価な文字列です)
シーケンスの目標は、繰り返されることのない一意の数字を作成することです。
$ dao -> nodeId = 1 ; // optional
$ dao -> tableSequence = ' snowflake ' ; // optional
$ dao -> createSequence (); // it creates a table (and it could create a store procedure) called snowflake and a function called next_snowflake(). You could create it only once.テーブルなしで新しいシーケンスを作成することが可能です。速いですが、衝突の問題がある可能性があります。
0.0001秒あたり複数の操作を行わない場合にのみ衝突フリー数を保証しますが、擬似乱数(時間内に0-4095)も追加するため、衝突の可能性は1/4095 (0.0001秒ごとに行われる2操作ごと)です。 Twitterのスノーフレーク番号に基づいています。すなわち。 1秒あたり100万件未満の操作を行っている場合(技術的には4500万)、衝突が安全です。
$ pdo-> get sequencephp([予測不可能= false])は、テーブルを使用せずにシーケンスを返します。このシーケンスは$ dao-> geteashenceよりも効率的ですが、ランダム値を使用して衝突を処理します。
upredictableが真実である場合、予測不可能な数を返します(数桁をめくって)
$ pdo -> getSequencePHP () // string(19) "3639032938181434317" $ dao -> getSequencePHP ( true ) // string(19) "1739032938181434311" $ pdo ->getSequence() // string(19) "3639032938181434317"
$ pdo -> getSequencePHP () // string(19) "3639032938181434317" $ pdo -> getSequence ( true ) // returns a sequence by flipping some values.
$ pdo -> getSequencePHP ( true ) // string(19) "1739032938181434311" | 分野 | 説明 | 例 |
|---|---|---|
| $ prefixbase | すべてのテーブルにプレフィックスを追加する必要がある場合 | $ this-> prefixbase = 'example_'; |
| $ internalcachecounter | 内部キャッシュのヒットのカウンター。 | $ this-> internalCachecounter =; |
| $ nodeid | シーケンス(スノーフレーク)で使用。 nodeidそれはノードの識別子です。 0..1023の間でなければなりません | $ this-> nodeid = 3; |
| $ TableSequence | テーブルシーケンスの名前(スノーフレーク) | $ this-> tableSequence = "tableSeq1"; |
| $ MASKS0 | 予測不可能な数値を生成したい場合(シーケンスで使用) | $ this-> masks0 = [0,1,2,3,4]; |
| $ MASKS1 | 予測不可能な数値を生成したい場合(シーケンスで使用) | $ this-> masks1 = [4,3,2,1,0]; |
| $ databaseType | 現在のタイプのデータベース。 ELコンストラクターを介して設定されています | echo $ this-> databaseType; |
| $サーバー | 現在のサーバーマシン | echo $ this-> server; |
| $ユーザー | 現在のユーザー | echo $ this-> user; |
| $ pwd | 現在のパスワード | echo $ this-> pwd; |
| $ db | 現在のデータベースまたはスキーマ(Oracleはこの値を無視します) | echo $ this-> db; |
| $ charset | デフォルトのチャーセットを設定します。コンストラクターを介して設定する必要があります | echo $ this-> charset; |
| $ isopen | データベースが接続されている場合、それは誤りです | if($ this-> isopen){…}; |
| $ THROWONERROR | 真(デフォルト)の場合、エラーが発生した場合にエラーをスローします。 falseの場合、実行は継続します | $ this-> throwonerror = false; |
| $ conn1 | PDOのインスタンス。設定するか、直接使用できます。 | $ this-> conn1-> pdostatement(..); |
| $ transactionOpen | トランザクションが開いている場合はtrue | if($ this-> transactionopen){…}; |
| $ readonly | データベースが読み取り専用モードかどうかの場合。本当なら、データベースに書き込むことを避ける必要があります | $ this-> readonly = true; |
| $ logfile | ログファイルの完全なファイル名。空の場合は、ログファイルを保存しません。ログファイルは1MBに制限されています | $ this-> logfile = "/folder/file.log"; |
| $ ERRORTEXT | 最後のエラーを保存します。 RungetとBegintryがリセットします | echo $ this-> errortext; |
| $ iSthrow | トト | $ this-> isthrow =; |
| $ loglevel | ログの現在のレベルを示します。 0 =ログなし(生産用)、3 =フルログ | $ this-> loglevel = 3; |
| $ lastquery | 最後のクエリが実行されました | echo $ this-> lastquery; |
| $ lastparam | 最後のパラメーター。それは連想配列です | echo $ this-> lastparam; |
このライブラリは、情報の暗号化/復号化を可能にします。
暗号化を設定するには、次のコマンドを使用できます。
$ this -> setEncryption ( 12345678 , '' , ' INTEGER ' ); // the type of encryption is integer and it only works with integers. It doesn't use a salt value
$ this -> setEncryption ( ' password ' , ' some-salt ' , ' AES-256-CTR ' ); // the password, the salt and the type of encryption (aes-256-ctr), you can use other methods
$ this -> setEncryption ( ' passwrd ' , '' , ' SIMPLE ' ); // the type of encryption is simple and it only works with primitive values. It doesn't use a salt.次に、値を暗号化および復号化できます
$ encrypted = $ this -> encrypt ( $ original ); // encrypt $original
$ original = $ this -> decrypt ( $ encrypted ); // decrypt $encrypted例:
$ this -> setEncryption ( ' 12345 ' , ' salt-1234 ' ); // it will use AES-256-CTR, the password and the salt must be secret.
// create user
$ this -> set ([ ' username ' => 1 , ' password ' => $ this -> encrypt ( $ password )])
-> from ( ' user ' )
-> insert ();
// validate user
$ user = $ this -> select ([ ' username ' , ' password ' ])
-> from ( ' user ' )
-> where ([ ' username ' , ' password ' ],[ 1 , $ this -> encrypt ( $ password )])
-> first ();
// $user= if false or null then the user does not exist or the password is incorrect. ログレベルを3に設定できます。操作が故障したときにログレベルが機能し、ログレベルが高くなり、ほとんどの情報が表示されます。
$ pdoOne -> logLevel = 3 ; // the highest for debug.デフォルトでは、PDOONEはPHPエラーをスローしますが、フィールド$ throwonerrorをfalseに設定することでそれを回避できます。
$ pdoOne -> throwOnError = false ; // it could be used in production. var_dump ( $ pdoOne -> lastQuery ); // it shows the last query
var_dump ( $ pdoOne -> lastParam ); // and it shows the last parameters.空の場合、それはログファイルを生成しません(PHPログファイルを使用)
$ pdoOne -> logFile = true ; PDOONEには、CLIでのみ利用可能な機能がいくつかあります。

次の行を実行します(libフォルダーで)
php pdoonecli.php
(または正しいフォルダーを指す)
PHP/var/web/vendor/eftec/lib/pdoonecli
フラグ「-i」を使用して、インタラクティブモードで入力できます。
TABキーを使用して、値をオートコンプリートすることができます(存在する場合)。

注:構成を保存およびロードすることもできます。
MySQLに接続し、テーブル「俳優」からCSVを生成します
# # via arguments
php pdoonecli --databasetype mysql --server 127.0.0.1 -u root -p abc.123 --database sakila -in actor -out csv
# # via user input (interactive)
php pdoonecli -i -in actor -out csvファイルに構成を保存します
php pdoonecli --databasetype mysql --server 127.0.0.1 -u root -p abc.123 --database sakila --saveconfig myconfigファイルから構成をロードします
php pdoonecli --loadconfig myconfig -in actor -out csvフラグ「-CLI」を使用してリポジトリクラスを生成できます

CLIはインタラクティブであり、構成をロードして保存できます。
この機能は、すぐに使用できるリポジトリクラスを生成します。
次の例を言ってみましょう
mysql:
PHP PDOONE.PHP - DATABASE MYSQL - SERVER 127.0.0.1:3306 -USER ROOT -P ABC.123 -DB SAKILA - Input "Actor" -Output ClassCode
SQLSRV:
PHP PDOONE.PHP - DATABASE SQLSRV - SERVER PCJC SQLEXPRESS -USER SA -P ABC.123 -DB SAKILA - INPUT "ACTOR" -OUTPUT CLASSCODE
データベースMySQL、IP:127.0.0.1およびデータベースSakilaに接続し、「アクター」テーブルを読み取ります。
次の結果が返されます
/**
* Generated by PdoOne Version 1.28
* Class ActorRepo
*/
class ActorRepo
{
const TABLE = ' Actor ' ;
const PK = ' actor_id ' ;
/** @var PdoOne */
public static $ pdoOne = null ;
/**
* It creates a new table<br>
* If the table exists then the operation is ignored (and it returns false)
*
* @param array $definition
* @param null $extra
*
* @return array|bool|PDOStatement
* @throws Exception
*/
public static function createTable ( $ definition , $ extra = null ) {
if (! self :: getPdoOne ()-> tableExist ( self :: TABLE )) {
return self :: getPdoOne ()-> createTable ( self :: TABLE , $ definition , self :: PK , $ extra );
}
return false ; // table already exist
}
// .....
}この機能は、最も一般的な操作を備えた新しいリポジトリクラスを生成します:挿入、リスト、更新、削除、取得、カウント、カウント、テーブル、ドロップテーブル、切り捨てテーブル
なぜクラスを生成する必要があるのですか? (1つを継承する代わりに)このCRUDクラスは出発点にすぎません。開発者は、コードを変更したり、新しい方法を追加したり、以前の方法を変更したりすることができます。
クラスを使用するには、次のコードを書くことができます。
// 1) option 1, inject an instance of $pdo
ActorRepo:: setPdoOne ( $ pdoOne ); // it inject the current connect to the database
// 2) option 2.
// If the global variable $pdoOne exists, then it is injected. (unless it is defined by using setPdoOne()
$ pdoOne = new PdoOne ( " mysql " , " 127.0.0.1 " , " root " , " abc.123 " , " sakila " , "" );
$ pdoOne -> connect ();
// 3) option 3
// If the global function pdoOne() exists, then it is used for obtain the instance.
function pdoOne () {
global $ pdo ;
if ( $ pdo === null ) {
$ pdo = new PdoOne ( ' mysql ' , ' 127.0.0.1 ' , ' root ' , ' abc.123 ' , ' sakila ' );
}
return $ pdo ;
}
$ actorActorRepo :: get ( 2 ); // it will read the actor with the pk=2 and it will return as an array.
$ actors = $ actorArray =ActorRepo:: select (); // it returns all the rows.または、次のようにPHPファイルを自動的に生成することもできます。
php pdoone.php -database mysql -server 127.0.0.1:3306 -user root -pwd abc.123 -db sakila -input "Actor" -output classcode> acorrepo.php
注:コードにはPHPタグ、名前空間、使用が不足していますが、他のすべてはここにあります。
クエリが取られ、クエリがフォーマットされた状態でPHPコードを返します。
例:
php pdoone.php -database mysql -server 127.0.0.1:3306 -user root -pwd abc.123 -db sakila -input "select * from Actor" -Output SelectCode
次のコードが生成されます。
/** @var array $result=array(["actor_id"=>0,"first_name"=>'',"last_name"=>'',"last_update"=>'']) */
$ result = $ pdo
-> select ( " * " )
-> from ( " actor " )
-> toList ();選択されたクエリまたはテーブルに基づいて、連想配列(デフォルト値を持つ)が生成されます。
PHP PDOONE.PHP -DATABASE MYSQL -SERVER 127.0.0.1:3306 -USER ROOT -PWD ABC.123 -DB SAKILA -INPUT "select * from Actor" -Output ArrayCode
それは返されます:
// ["actor_id"=>0,"first_name"=>'',"last_name"=>'',"last_update"=>'']クエリの結果をJSONとして返します
PHP PDOONE.PHP -DATABASE MYSQL -SERVER 127.0.0.1:3306 -USER ROOT -PWD ABC.123 -DB Sakila -Input "select * from Actor" -Output JSON
それは返されます:
[{ "actor_id" : " 1 " , "first_name" : " PENELOPE " , "last_name" : " GUINESS " , "last_update" : " 2006-02-15 01:34:33 " }
,{ "actor_id" : " 2 " , "first_name" : " NICK " , "last_name" : " WAHLBERG " , "last_update" : " 2006-02-15 01:34:33 " }
,{ "actor_id" : " 3 " , "first_name" : " ED " , "last_name" : " CHASE " , "last_update" : " 2006-02-15 01:34:33 " }
,{ "actor_id" : " 4 " , "first_name" : " JENNIFER " , "last_name" : " DAVIS " , " last_update " }]クエリの結果をJSONとして返します
php pdoone.php -database mysql -server 127.0.0.1:3306 -user root -pwd abc.123 -db sakila -input "select * from Actor" -Output CSV
それは返されます:
actor_id,first_name,last_name,last_update
1,"PENELOPE","GUINESS","2006-02-15 01:34:33"
2,"NICK","WAHLBERG","2006-02-15 01:34:33"
3,"ED","CHASE","2006-02-15 01:34:33"
4,"JENNIFER","DAVIS","2006-02-15 01:34:33"
CLIの代わりに、ライブラリにはインターフェイスビジュアルがあります。 CLIのすべての操作を行います。

メソッドを呼び出すだけでrender()
<?php
use eftec PdoOne ;
use mapache_commons Collection ;
include " ../vendor/autoload.php " ;
$ dao = new PdoOne ( " test " , " 127.0.0.1 " , " dummy " , " dummy " , " dummy " ); // we need any connection.
$ dao -> logLevel = 3 ;
$ dao -> render ();フォルダーの例/testui.phpに例があります
次のコマンドは通常、単独で実行されます(メソッドのチェーンではありません)
| 方法 | 説明 | 例 |
|---|---|---|
| createTable() | リポジトリ内の定義を使用してテーブルとインデックスを作成します | tableaparentrepo :: createTable(); |
| createforeignkeys() | テーブルのすべての外部キーを作成します | tableaparentrepo :: createforeignkeys(); |
| droptable() | テーブルをドロップします | tableaparentrepo :: droptable(); |
| truncate() | テーブルを切り捨てます | tableaparentrepo :: truncate(); |
| validTable() | テーブルが変更されていないかどうかを検証します | $ ok = tableaparentrepo :: validTable(); |
TablaParentRepo:: createTable ();
TablaParentRepo:: createForeignKeys ();
TablaParentRepo:: dropTable ();
TablaParentRepo:: truncate ();
// We don't have a method to alter a table.
$ ok =TablaParentRepo:: validTable (); // it returns true if the table matches with the definition stored into the clasネストされた演算子は、私たちの一連の方法の間にあるべき方法です。
classrepo :: op():: where():: finalop()is✅
classrepo :: op():: op():: where()はチェーンを開いたままにします
例えば:
// select *
// from table
// inner join table2 on t1=t2
// where col=:arg
// and col2=:arg2
// group by col
// having col3=:arg3
// order by col
// limit 20,30
$ results = $ pdo -> select ( ' * ' )
-> from ( ' table ' )
-> innerjoin ( ' table2 on t1=t2 ' )
-> where ( ' col=:arg and col2:=arg2 ' ,[ 20 , 30 ])
// it also works with ->where('col=:arg',20)->where('col2'=>30)
// it also works with ->where('col=?',20)->where('col2=?'=>30)
-> group ( ' col ' )
-> having ( ' col3=:arg3 ' , 400 )
-> order ( ' col ' )
-> limit ( ' 20,30 ' )
-> toList (); // end of the chain| 方法 | 説明 | 例 |
|---|---|---|
| どこ() | チェーンに場所を追加します | tableaparentrepo :: where() |
| 注文() | チェーンに注文を追加します | tableaparentrepo :: order() |
| グループ() | チェーンにグループを追加します | tableaparentrepo :: group() |
| limit() | 結果が制限されます | tableaparentrepo :: lime() |
| ページ() | 制限に似ていますが、ページを使用します | tableaparentrepo :: page() |
| innerjoin() | クエリに内部結合を追加します | tableaparentrepo :: innerjoin() |
| 左() | クエリに左結合を追加します | tableaparentrepo :: left() |
| 右() | クエリに右結合を追加します | tableaparentrepo :: right() |
データベースにDQL(Query)コマンドを生成するさまざまな方法があります。
操作が失敗した場合、それらは虚偽を返し、例外をトリガーする可能性があります。
次の方法は、チェーンの最後にある必要があります。例:
classrepo :: op():: op():: tolist()は✅です
classrepo :: op():: tolist():: op()は例外をトリガーします
| 指示 | 説明 | 例 |
|---|---|---|
| tolist() | 一連の要素を返します | $ data = tablenamerepo :: tolist(); // tableRepoから *を選択します $ data = tablenamerepo :: where( 'a1 =?'、[$ value]):: tolist(); // a1 = $ valueからtablerepoから *を選択します |
| 初め() | 単純な行を返します | $ data = tablenamerepo :: first($ pk); // pk = $ pk(常に1つまたはゼロ値を返すtablererepoから * select * $ data = tablenamerepo :: where( 'a1 =?'、[$ value]):: first(); //最初の値を返します(または発見されていない場合はfalse) |
| 存在する() | プライマリキーが存在する場合はtrueを返します | $ data = tablenamerepo ::存在する($ pk); //オブジェクトが存在する場合はtrueを返します。 |
| カウント() | クエリで行数を返します | $ data = tablenamerepo :: count($条件); $ data = tablenamerepo :: where( 'a1 =?'、[$ value]):: count(); |
次の方法では、データベースに値を挿入、更新、または削除できます。
| 方法 | 説明 | 例 |
|---|---|---|
| 入れる | データベースに値を挿入します。アイデンティティを返すことができます | $ ID = tableaparentrepo :: insert($ obj); |
| アップデート | 値をデータベースに更新します。 | tableaparentrepo :: update($ obj); |
| 消去 | データベースから値を削除します。 | tableaparentrepo :: delete($ obj); |
| DeleteByid | データベースから値(条件としてプライマリキーを使用)を削除します。 | tableaparentrepo :: deletebyid($ pk); |
// where obj is an associative array or an object, where the keys are the name of the columns (case sensitive)
$ identity =TablaParentRepo:: insert ( $ obj );
TablaParentRepo:: update ( $ obj );
TablaParentRepo:: delete ( $ obj );
TablaParentRepo:: deleteById (id);モデルを検証することが可能です。モデルは、データベースの情報を使用して検証され、列のタイプ、長さを使用して、値がnullを許可する場合、およびそれがIDの場合(自動数値)。
$ obj =[ ' IdUser ' => 1 , ' Name ' ='John Doe'];
UserRepo:: validateModel ( $ obj , false ,[ ' _messages ' ]); // returns true if $obj is a valid User.再帰配列は、読み取りまたは取得または比較できる値を持つ文字列の配列です。たとえば、条件付きでテーブルに参加します。 PDOONEは直接使用しませんが、_Basepdoonerepoはそれを使用します(_Basepdoonerepoは、リポジトリサービスクラスを自動的に生成するときに使用されるクラスです)。
例
$ this -> select ( ' * ' )-> from ( ' table ' )-> recursive ([ ' table1 ' , ' table1.table2 ' ]);
// some operations that involves recursive
if ( $ this -> hasRecursive ( ' table1 ' )) {
$ this -> innerJoin ( ' table1 on table.c=table1.c ' );
}
if ( $ this -> hasRecursive ( ' table1.table2 ' )) {
$ this -> innerJoin ( ' table1 on table1.c=table2.c ' );
}
$ r = $ this -> toList (); // recursive is resetted. 再帰配列を設定します。
この値は、チェーンメソッドが終了するたびにリセットされます。
再帰配列を取得します。
再帰的な針がある場合、それは真実です。
$ this->再帰が['*']である場合、それは常にtrueを返します。
$ this -> select ( ' * ' )-> from ( ' table ' )-> recursive ([ ' * ' ]);
$ this -> hasRecursive ( ' anything ' ); // it always returns true. | 図書館 | 入れる | findpk | 水和物 | と | 時間 |
|---|---|---|---|---|---|
| PDO | 671 | 60 | 278 | 887 | 3,74 |
| PDOONE | 774 | 63 | 292 | 903 | 4,73 |
| lessql | 1413 | 133 | 539 | 825 | 5,984 |
| Yiim | 2260 | 127 | 446 | 1516 | 8,415 |
| yiimwithcache | 1925年 | 122 | 421 | 1547 | 7,854 |
| yii2m | 4344 | 208 | 632 | 1165 | 11,968 |
| yii2marrayhydrate | 4114 | 213 | 531 | 1073 | 11,22 |
| yii2mscalarhydrate | 4150 | 198 | 421 | 516 | 9,537 |
| propel20 | 2507 | 123 | 1373 | 1960年 | 11,781 |
| propel20withcache | 1519 | 68 | 1045 | 1454 | 8,228 |
| propel20formatondemand | 1501 | 72 | 994 | 1423 | 8,228 |
| ドクトリネム | 2119 | 250 | 1592 | 1258 | 18,139 |
| Doctrinemwithcache | 2084 | 243 | 1634 | 1155 | 17,952 |
| Doctrinemarrayhydrate | 2137 | 240 | 1230 | 877 | 16,83 |
| Doctrinemscalarhydrate | 2084 | 392 | 1542 | 939 | 18,887 |
| DoctrinemwithOutProxies | 2119 | 252 | 1432 | 1960年 | 19,822 |
| 雄弁 | 3691 | 228 | 708 | 1413 | 12,155 |
PDOONEはPDOに少しOveheadを追加しますが、PDOのラッパーです。
これは、PDOONEが更新され、ORMによって生成された1つのクラスを使用していることを意味します。このクラスは再生する必要があります。
一言で言えば:
すべてのメジャーバージョンは、古いコードを破る可能性があることを意味します。 IE 1.0-> 2.0
すべてのマイナーバージョンは、新しい機能を追加することを意味します。つまり、1.5-> 1.6(新しい方法)
すべての小数バージョンは、以前の機能をパッチ/修正/リファクタリングすることを意味します。
4.10 2024-09-06
4.9.2 2024-08-20
4.9.1 2024-08-20
4.9 2024-08-02
4.8 2024-07-06
4.7.1 2024-06-07
4.7 2024-06-07
4.6.2 2024-03-02
4.6.1 2024-03-02
4.6 2024-03-02
4.4 2023-12-12
4.3.3 2023-09-05
4.3.2 2023-09-05
4.3.1 2023-09-02
4.3 2023-07-01
4.2 2023-04-07
4.1.2 2023-03-21
4.1.1 2023-03-21
4.1 2023-03-20
4.0.1 2023-03-11
4.00 2023-11-03
3.16 2023-12-02
3.15 2023-02-03
3.14 2023-01-30
3.13 2023-01-26
3.12.2 2022-09-03
3.12.1 2022-08-26
3.12 2022-08-14
3.11.1 2022-07-30
3.11 2022-07-30
3.10 2022-07-30
3.9 2022-07-23
3.8.1 2022-07-23
3.8 2022-07-22
3.7 2022-07-16
3.6 2022-07-07
3.5 2022-07-06
3.3 2022-06-27
3.2 2022-06-27
3.1.6 2022-06-24
3.1.5 2022-06-23
3.1.4 2022-06-21
3.1.3 2022-06-18
3.1.2 2022-06-18
3.1.1 2022-06-17
3.1 2022-06-11
3.0 2022-06-1
2.32 2022-03-20
2.31 2022-03-04
2.30 2022-02-28
2.29 2022-02-20
2.27 2022-02-19
2.26 2022-02-19
2.25 2022-02-01
2.24.1 2022-02-06
2.24 2022-02-06
2.23 2022-02-04
2.22.2 2022-02-01
2.22.1 2022-01-03
2.22 2022-01-30
2.21 2022-01-28
However, it is far from perfect.
2.20 2022-01-04
2.19
2.18
2.16
2.15 2021-07-24
2.14.3 2021-06-15
2.14.2 2021-06-13
2.14.1 2021-06-09
2.14 2021-06-04
_BasePdoOneRepo now works more closely with the class PdoOneQuery , so each query is a different instance.
[fix] PdoOne dateConvertInput() does not crash when the value is not a date.
[fix] PdoOne throwError() does not stack errors but still triggers the last error (if any).
[changes] ❗ PdoOne aggregate functions (sum,min,max,avg) now returns a value instead of generating a query.
$result=$pdo->sum('xxx')->firstScalar(); // before $result=$pdo->sum('xxx'); // 今
[fix] PdoOne generateCodeArray() used for the generation of classes, returns the correct name when it is set.
[changes] _BasePdoOneRepo : reset(),getQuery(),dropTable(),useCache(),limit(),newQuery(),order(),innerjoin(),left() ,right()
[changes] PdoOneQuery : Multiples changes.
2.13.1 2021-05-22
2.13 2021-04-17
2.12 2021-04-17
2.11.1 2021-04-17
2.11 2021-04-17
2.10.3 2021-04-14
2.10.2 2021-04-06
2.10.1 2021-04-05
2.10 2021-04-04
2.9.4 2021-03-22
2.9.3 2021-02-22
2.9.2 2021-02-18
2.9.1 2021-02-16
2.9 2021-02-16
2.8 2021-02-13
2.7.1 2021-01-21
2.7 2021-01-10
2.6.3 2020-10-16
2.6.2 2020-10-09
2.6.1 2020-09-24
2.6 2020-09-17
2.5 2020-09-13
2.4.1 2020-09-13
2.4 2020-09-06
2.3 2020-09-06
2.2.6 2020-09-03
2.2.5 2020-08-30
2.2.3 2020-08-23
2.2.2 2020-08-17
2.2.1 2020-08-16
2.2 2020-08-14
$ this -> setUseInternalCache ( true );
$ rows = $ this -> select ( ' * ' )-> from ( ' table ' )-> where ([ ' i ' => 1 ])-> toList (); // read from the database
// ...
$ rows2 = $ this -> select ( ' * ' )-> from ( ' table ' )-> where ([ ' i ' => 1 ])-> toList (); // read from memory
// ...
$ rows3 = $ this -> select ( ' * ' )-> from ( ' table ' )-> where ([ ' i ' => 2 ])-> toList (); // read from the database because the query is in
// memory but the parameters are different
echo $ this -> internalCacheCounter ; The internal cache is tested with runRawQuery (if returns an array), toList(), meta() and first()
2.0.1 2020-08-12
2.0 2020-08-11
1.55.1 2020-08-05
1.55 2020-8-05
1.54 2020-8-02
1.53 2020-7-27
1.52 2020-7-19
1.51 2020-7-18
1.50 2020-7-04
1.49 2020-6-19
1.48 2020-6-15
1.47 2020-6-14
1.46 2020-6-13
1.45.1 2020-6-11
1.45 2020-6-7
1.44.2 2020-6-3
1.44.1 2020-6-2
1.44 2020-5-31
1.43 2020-5-31
1.42 2020-5-29
1.41.2 2020-5-29
1.41.1 2020-5-28
1.41 2020-5-28
1.40.1 2020-5-27
1.40 2020-05-21
1.39 2020-05-12
1.38 2020-05-10
1.37 2020-05-03
1.36 2020-05-03
1.35.1 2020-04-30
1.35 2020-04-28
1.34.2 2020-04-27
1.34.1 2020-04-27
1.34 2020-04-27
1.33 2020-04-15
1.32.1 BasePdoOneRepo added version 2.0
1.32 2020-04-12
1.31.1 2020-04-11
1.31 2020-04-11
1.30 2020-04-10
1.29 2020-04-10
1.28.1 2020-04-06
1.28 2020-04-06
1.24 2020-03-26
1.23.1 2020-03-10
1.23 2020-03-10
1.22 2020-02-08
1.21 2020-02-07
1.20 2020-jan-25
1.19 2020-jan-15
1.16 2020-jan-14
1.15 2019-dec-29
1.14 2019-dec-26
1.13 2019-dec-26
1.12 2019-oct-20 Added argument (optional) ->toList($pdomodel) Added method ->toListSimple()
1.11 2019-oct-01 1.11 It is still compatible with php 5.6.Added to composer.json
1.10 2019-oct-01 1.10 Added method dateConvert(). Added trace to the throw.
1.9 2019-aug-10 1.8 republished
1.8 2019-aug-10 Added a date format. Methods dateSql2Text() and dateText2Sql()
1.7 2019-jun-23 Added some benchmark. It also solves a problem with the tags. Now: table.field=? is converted to table . field =?
1.6 2019-jun-22 affected_rows() returns a correct value.
1.5 2019-may-31 some cleanups. columnTable() returns if the column is nullable or not.
1.4 2019-may-30 insertobject()
1.3 2019-may-23 New changes
1.2 2019-may-22 New fixed.
1.1 2019-may-21 Some maintenance
1.0 2019-may-21 First version