Pdoone. É um invólucro simples para a biblioteca PDO da PHP compatível com o SQL Server (2008 R2 ou superior), MySQL (5.7 ou superior) e Oracle (12.1 ou superior).
Esta biblioteca tenta trabalhar o mais rápido possível . A maioria das operações são gerentes simples de cordas/matrizes e trabalham no metal nu da biblioteca PDO, mas também permite criar um ORM usando a extensão EFTEC/PdoOneorm.
Vire isso
$ 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 ();nisso
$ products = $ pdoOne
-> select ( " * " )
-> from ( " myTable " )
-> where ( " name = ? " ,[ $ _POST [ ' name ' ]])
-> toList ();ou usando o ORM (usando a Biblioteca Eftec/PdoOneorm)
ProductRepo // this class was generated with echo $pdoOne()->generateCodeClass(['Product']); or using the cli.
:: where ( " name = ? " ,[ $ _POST [ ' name ' ]])
:: toList ();| ExampleTicketphp | Exemplo de cupcakes | Exemplo de pesquisa | Exemplo de método diferente |
|---|---|---|---|
![]() | ![]() | ![]() |
Mais exemplos:
Exemplo MySQL PHP e PDO usando Pdoone
Esta biblioteca requer Php 7.1 e superior, e requer a PDO de extensão e a extensão PDO-MYSQL (MYSQL), PDO-SQLSRV (SQL Server) ou PDO-OCI (Oracle)
Edite composer.json o próximo requisito e atualize o Composer.
{
"require" : {
"eftec/PdoOne" : " ^4.0.1 "
}
}ou instale -o via CLI usando
O compositor requer eftec/pdoone
Basta baixar a pasta Lib da biblioteca e colocar seu projeto de pasta. Em seguida, você deve incluir todos os arquivos incluídos nele.
Crie uma instância da classe pdoone da seguinte maneira. Em seguida, você pode abrir a conexão usando o método Connect () ou 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 ();onde
$ dao = novo pdoone ("mysql", "127.0.0.1", "root", "abc.123", "sakila", "");
O Oracle é complicado de instalar. No Windows, na pasta BIN da Oracle Home, você deve copiar toda a DLL para a pasta PHP e a pasta Apache.
Com o método runRawQuery () , poderíamos executar um comando diretamente para PDO com ou sem parâmetros. E poderia devolver uma pdostatement ou uma matriz . É útil quando queremos velocidade.
RunRawQuery ($ Rawsql, $ param, $ ReturnArray, $ fetchmode, $ fetchargument)
String $ RAWSQL A consulta para executar a matriz | null $ param [TIPO1, VALUE1, TIPO2, VALOR2] ou [nome1 => Valor, nome2 = value2] BOOL $ ReturnArray Se true (padrão), ele retorna uma matriz. Se False, ele retorna um pdostatement Int $ fetchmode indica que o modo busca. Exemplo: PDO :: fetch_assoc null $ fetchArgument O argumento do FetchMode.
$ sql = ' select * from table where id=1 ' ;
$ pdoStatement = $ pdoOne -> runRawQuery ( $ sql ,[], false ); // [] are the parametersMas poderíamos mudar para retornar uma matriz
$ sql = ' select * from table where id=1 ' ;
$ values = $ pdoOne -> runRawQuery ( $ sql ); // [] are the parametersTambém poderíamos passar os parâmetros.
$ 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.Observe que esta biblioteca usa declarações preparadas, por isso está livre de injeção de SQL (se você usar parâmetros)
$ 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.Com o método RunQuery (), poderíamos executar uma declaração preparada no PDO. É útil quando queremos passar argumentos para ele. RunQuery () requer um PDO preparado .
Este método não é recomendado, a menos que você já esteja trabalhando com instruções de PDO e não deseja adaptar todo o seu código.
$ 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 );Você pode usar o construtor de consultas para construir seu comando. Você pode verificar o capítulo sobre o Consulta Builder (DQL) para obter mais informações.
// query builder
$ pdoOne -> set ([ ' name ' => ' cocacola ' ])
-> from ( ' product ' )
-> insert ();A biblioteca eftec pdoOneorm permite criar um [orm] (#orm) de suas tabelas. Se você é gerado um ORM, poderá usar o próximo código
ProductRepo:: toList ([ ' category ' => ' drink ' ]);Onde o ProductTrepo é uma classe de serviço gerada usando o ORM.
Por padrão, o PdoOne executa as consultas no modo PDO :: fetch_assoc que você pode mudar executando as consultas como:
$ pdo -> setFechMode ( PDO :: FETCH_CLASS , ' stdClass ' )-> runRawQuery ( $ query );
// or you can run as
$ pdo -> runRawQuery ( $ query , null , true , false , null , PDO :: FETCH_CLASS , ' stdClass ' )O pdoone permite 5 tipos de datas.
Formato SQL É o formato como a data é armazenada no banco de dados. Depende do tipo de banco de dados. Por exemplo, o MySQL poderia usar o formato YMD.
Formato humano É o formato como o usuário final parece nossa data.
Formato de data ISO . É o formato como o valor pode ser transportado e serializado.
Timestamp : conta o número de segundos após 1-1-1970
Classe / PHP Class : é um objeto DateTime .
Existem 3 métodos para executar uma transação:
| Método | Descrição |
|---|---|
| startTransaction () | Inicia uma transação. Dependendo do banco de dados do tipo, ele pode ser empilhado ou não. |
| comprometer-se() | Cometer (e fechar) uma transação |
| reversão () | Reversão (e fecha) uma transação |
Exemplo:
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.
}Retorna true se a tabela existir (banco de dados/esquema atual)
Retorna as estatísticas (como uma matriz) de uma coluna de uma tabela.
$ stats = $ pdoOne -> statValue ( ' actor ' , ' actor_id ' );| min | máx | Avg | soma | contar |
|---|---|---|---|---|
| 1 | 205 | 103.0000 | 21115 | 205 |
Retorna todas as colunas de uma tabela
$ result = $ pdoOne -> columnTable ( ' actor ' );| Colname | Coltype | Colsize | COLPRES | colcale | iskey | isIdentity |
|---|---|---|---|---|---|---|
| ator_id | smallint | 5 | 0 | 1 | 1 | |
| primeiro nome | Varchar | 45 | 0 | 0 | ||
| sobrenome | Varchar | 45 | 0 | 0 | ||
| last_update | Timestamp | 0 | 0 |
Retorna todas as chaves estrangeiras de uma tabela (tabela de origem)
Cria uma tabela usando uma definição e chave primária.
Nota: Você pode gerar um código para criar uma tabela usando uma tabela existente executando a CLI (ClassCode de saída)
php pdoone.php -database mysql -server 127.0.0.1 -User raiz -pwd abc.123 -db sakila -input Film -Output ClassCode
Exemplo: (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 ' ); Exemplo (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 "
]);Ele retorna uma lista de tabelas ordenadas por dependência (de nenhum dependente para mais dependente)
Nota : Esta operação não é infalível porque as tabelas podem ter referências circulares.
$ 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> " ;Ele valida uma tabela se a tabela corresponder à definição aplicada pelos valores.
$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));
Ele retorna todas as chaves estrangeiras de uma mesa.
$ result = $ pdoOne -> foreignKeyTable ( ' actor ' );| Colocal | Tablerem | Colrem |
|---|---|---|
| Customer_id | cliente | Customer_id |
| Rental_id | aluguel | Rental_id |
| Staff_id | funcionários | Staff_id |
Você também pode construir uma consulta processual.
Exemplo:
$ results = $ pdoOne -> select ( " * " )-> from ( " producttype " )
-> where ( ' name=? ' , [ ' Cocacola ' ])
-> where ( ' idproducttype=? ' , [ 1 ])
-> toList (); Indica as colunas para retornar. O argumento é um comando SQL, por isso permite qualquer operação que o suporte ao banco de dados, incluindo funções, constantes, operadores, alias e outros.
$ results = $ pdoOne -> select ( " col1,col2 " ); //...Gera a consulta: selecione col1, col2 ....
$ results = $ pdoOne -> select ( " select * from table " ); //->...Gera a consulta: Selecione * da tabela ....
Gera uma consulta que retorna uma contagem de valores. É uma macro do método 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 tableGera uma consulta que retorna o valor mínimo de uma coluna. Se $ arg estiver vazio, ele usa $ sql para o nome da coluna, é uma macro do método 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 tableGera uma consulta que retorna o valor máximo de uma coluna. Se $ arg estiver vazio, ele usa $ sql para o nome da coluna, é uma macro do método 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 tableGera uma consulta que retorna o valor da soma de uma coluna. Se $ arg estiver vazio, ele usa $ sql para o nome da coluna, é uma macro do método 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 tableGera uma consulta que retorna o valor médio de uma coluna. Se $ arg estiver vazio, ele usa $ sql para o nome da coluna, é uma macro do método 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 tableGera um comando select.
$ results = $ pdoOne -> select ( " col1,col2 " )-> distinct (); //...Gera a consulta: selecione col1 distinto , col2 ....
NOTA: -> Distinct ('exclusivo') retorna selecionar exclusivo ..
Gera um comando "de" SQL.
$ results = $ pdoOne -> select ( " * " )-> from ( ' table ' ); //...Gera a consulta: selecione * da tabela
$ tabelas pode ser uma única tabela ou uma construção SQL. Para o Examp, o próximo comando é válido:
$ results = $ pdoOne -> select ( " * " )-> from ( ' table t1 inner join t2 on t1.c1=t2.c2 ' ); //...Gera um comando where.
$ results = $ pdoOne -> select ( " * " )
-> from ( ' table ' )
-> where ( ' p1=1 ' ); //...O Where poderia ser expresso de maneiras diferentes.
É possível escrever o Where sem parâmetros da seguinte forma:
$ 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 % " ]);Também funciona
// (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]); É uma definição abreviada de uma consulta usando uma matriz associativa, onde a chave é o nome da coluna e o valor é o valor a ser comparado
Funciona apenas com igualdade (=) e o operador lógico 'e' (o tipo é definido automaticamente)
// 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 ' ]); Além disso, é possível especificar o tipo de parâmetro.
// 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 ' ]]); Você também pode usar uma matriz associativa como argumento e parâmetros nomeados na consulta
$ results = $ pdoOne -> select ( " * " )-> from ( " table " )
-> where ( ' condition=:p1 and condition2=:p2 ' ,[ ' p1 ' => ' Coca-Cola ' , ' p2 ' => 1 ])
-> toList ();Gera a consulta: Selecione * da tabela onde condição =? (Coca-Cola) e Condition2 =? (1)
Gera a consulta: selecione * da tabela onde P1 = 1
Nota: ArrayParameters é uma matriz da seguinte maneira: Tipo, valor.
Onde o tipo é i = número inteiro, d = duplo, s = string ou b = blob. Em caso de dúvida, use "s" (consulte a tabela abaixo)
Exemplo de ArrayParameters:
[1, 'Olá', 20,3, 'mundo']
$ results = $ pdoOne -> select ( " * " )
-> from ( ' table ' )
-> where ( ' p1=? ' ,[ 1 ]); //...Gera a consulta: Selecione * da tabela onde P1 =? (1)
$ results = $ pdoOne -> select ( " * " )
-> from ( ' table ' )
-> where ( ' p1=? and p2=? ' ,[ 1 , ' hello ' ]); //...Gera a consulta: selecione * da tabela onde P1 =? (1) e P2 =? ('Hello')
Observação. onde poderia ser aninhado.
$ results = $ pdoOne -> select ( " * " )
-> from ( ' table ' )
-> where ( ' p1=? ' ,[ 1 ])
-> where ( ' p2=? ' ,[ ' hello ' ]); //...Gera a consulta: selecione * da tabela onde P1 =? (1) e P2 =? ('Hello')
Você também pode usar:
$ results = $ pdoOne -> select ( " * " )-> from ( " table " )
-> where ([ ' p1 ' => ' Coca-Cola ' , ' p2 ' => 1 ])
-> toList ();Gera a consulta: selecione * da tabela onde P1 =? (Coca-Cola) e P2 =? (1)
Gera um comando de ordem.
$ results = $ pdoOne -> select ( " * " )
-> from ( ' table ' )
-> order ( ' p1 desc ' ); //...Gera a consulta: Selecione * FROM ORDEM TABLE POR P1 DESC
Gera um comando de grupo.
$ results = $ pdoOne -> select ( " * " )
-> from ( ' table ' )
-> group ( ' p1 ' ); //...Gera a consulta: Selecione * do grupo de tabela por P1
Gera um comando tendo.
Nota: Ele usa os mesmos parâmetros que onde ()
$ results = $ pdoOne -> select ( " * " )
-> from ( ' table ' )
-> group ( ' p1 ' )
-> having ( ' p1>? ' , array ( 1 )); //...Gera a consulta: Selecione * do grupo de tabela por P1 com P1>? (1)
NOTA: Tendo poderia ser aninhado tendo ()-> tendo ()
Nota: Ter poderia estar sem parâmetros com ('col> 10')
Execute a consulta gerar.
NOTA Se o retorno for verdadeiro, ele retornará uma matriz associativa. Se o retorno é falso, ele retorna um mysqli_result
Nota: Redefina os parâmetros atuais (como a seleção atual, de, onde, etc.)
É uma macro de rungen () . Ele retorna uma matriz associativa ou falsa se a operação falhar.
$ results = $ pdoOne -> select ( " * " )
-> from ( ' table ' )
-> toList (); Ele retorna uma pdostatement da consulta atual
Nota: Se você deseja fazer loop da instrução, poderá usar o Fetchloop ()
Exemplo :
$ stmt = $ pdoOne -> select ( " * " )
-> from ( ' table ' )
-> toPdoStatement ();
while ( $ row = $ stmt -> fetch ()) {
// do something
} Ele busca uma consulta para cada linha.
Este método pode ser usado quando não queremos ler todas as informações de uma só vez, para que você possa ler e processar cada linha separadamente
Exemplo :
$ this -> select ( ' select id,name from table ' )
-> fetchLoop ( static function ( $ row ) { return ( $ row );}, PDO :: FETCH_ASSOC )Ele retorna um metacodo (definições) de cada coluna de uma consulta.
$ results = $ pdoOne -> select ( " * " )
-> from ( ' table ' )
-> toMeta (); ou
$ results = $ pdoOne -> toMeta ( ' select * from table ' ); resultado:
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)
}
}
É uma macro de Rungen. Ele retorna uma matriz indexada da primeira coluna
$ results = $ pdoOne -> select ( " * " )
-> from ( ' table ' )
-> toListSimple (); // ['1','2','3','4'] Ele retorna uma matriz associativa, onde o primeiro valor é a chave e a segunda é o valor.
Se o segundo valor não existir, ele usa o índice como valor (primeiro valor).
$ results = $ pdoOne -> select ( " cod,name " )
-> from ( ' table ' )
-> toListKeyValue (); // ['cod1'=>'name1','cod2'=>'name2'] É uma macro de Rungen. Ele retorna um mysqli_result ou nulo.
$ results = $ pdoOne -> select ( " * " )
-> from ( ' table ' )
-> toResult (); // Ele retorna o primeiro escalar (um valor) de uma consulta. Se $ Colname for nulo, ele usa a primeira coluna.
$ count = $ this -> count ( ' from product_category ' )-> firstScalar ();É uma macro de Rungen. Ele retorna a primeira linha, se não, se não, retorna falsa, como uma matriz associativa.
$ results = $ pdoOne -> select ( " * " )
-> from ( ' table ' )
-> first (); É uma macro de Rungen. Ele retorna a última linha (se houver, se não, retorna falsa) como uma matriz associativa.
$ results = $ pdoOne -> select ( " * " )
-> from ( ' table ' )
-> last (); Às vezes é mais eficiente para executar o pedido () e primeiro () porque o último () lê todos os valores.
Ele retorna o comando sql e string.
$ sql = $ pdoOne -> select ( " * " )
-> from ( ' table ' )
-> sqlGen ();
echo $ sql ; // returns select * from table
$ results = $ pdoOne -> toList (); // executes the queryNota: ele não redefine a consulta.
Existem quatro maneiras de executar cada comando.
Digamos que queremos adicionar um número inteiro na coluna col1 com o valor 20
Esquema e valores usando uma lista de valores : onde o primeiro valor é a coluna, o segundo é o tipo de valor (i = inteiro, d = duplo, s = string, b = blob) e a segunda matriz contém os valores.
$ pdoOne -> insert ( " table "
,[ ' col1 ' ]
,[ 20 ]);Esquema e valores na mesma lista : onde o primeiro valor é a coluna, o segundo é o tipo de valor (i = inteiro, d = duplo, s = string, b = blob) e o terceiro é o valor.
$ pdoOne -> insert ( " table "
,[ ' col1 ' , 20 ]);Esquema e valores usando duas matrizes associativas :
$ pdoOne -> insert ( " table "
,[ ' col1 ' ]
,[ ' col1 ' => 20 ]);Esquema e valores usando uma única matriz associativa : o tipo é calculado automaticamente.
$ pdoOne -> insert ( " table "
,[ ' col1 ' => 20 ]);Gera um comando de inserção.
$ pdoOne -> insert ( " producttype "
,[ ' idproducttype ' , ' name ' , ' type ' ]
,[ 1 , ' cocacola ' , 1 ]);Usando corrente aninhada (matriz única)
$ pdoOne -> from ( " producttype " )
-> set ([ ' idproducttype ' , 0 , ' name ' , ' Pepsi ' , ' type ' , 1 ])
-> insert ();Usando o conjunto de múltiplas cadeias aninhadas
$ pdoOne -> from ( " producttype " )
-> set ( " idproducttype=? " ,[ 101 ])
-> set ( ' name=? ' ,[ ' Pepsi ' ])
-> set ( ' type=? ' ,[ 1 ])
-> insert ();ou (o tipo é definido, no possível, automaticamente pelo MySQL)
$ pdoOne -> from ( " producttype " )
-> set ( " idproducttype=? " ,[ 101 ])
-> set ( ' name=? ' , ' Pepsi ' )
-> set ( ' type=? ' , 1 )
-> insert (); $ pdoOne -> insertObject ( ' table ' ,[ ' Id ' => 1 , ' Name ' => ' CocaCola ' ]);Usando o conjunto declarativo de cadeia aninhada
$ pdoOne -> from ( " producttype " )
-> set ( ' (idproducttype,name,type) values (?,?,?) ' ,[ 100 , ' Pepsi ' , 1 ])
-> insert ();Gera a consulta: inserir em produttype (idproducttype, nome, tipo) valores (?,?) ....) ....
Gera um comando de inserção.
$ 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 (); // updateou
$ pdoOne -> from ( " producttype " )
-> set ( " name=? " , ' Captain-Crunch ' ) //set
-> set ( " type=? " , 6 ) //set
-> where ( ' idproducttype=? ' ,[ 6 ]) // where
-> update (); // updateGera a consulta: atualizar
namedo produto productType =?,type=? ondeidproducttype=? ....
Gera um comando de exclusão.
$ pdoOne -> delete ( " producttype "
,[ ' idproducttype ' ] // where
,[ 7 ]); // where $ pdoOne -> delete ( " producttype "
,[ ' idproducttype ' => 7 ]); // whereGera a consulta: Exclua do ProductType onde
idproducttype=? ....
Você também pode excluir por meio de uma cadeia de construtores DQL.
$ pdoOne -> from ( " producttype " )
-> where ( ' idproducttype=? ' ,[ 7 ]) // where
-> delete (); $ pdoOne -> from ( " producttype " )
-> where ([ ' idproducttype ' => 7 ]) // where
-> delete (); Gera a consulta: Exclua do ProductType onde
idproducttype=? ....
É possível cache opcionalmente o resultado das consultas. A duração da consulta também é definida na consulta. Se o resultado da consulta não for armazenado em cache, ela será calculada normalmente (executando a consulta no banco de dados). Para identificar uma consulta como exclusiva, o sistema gera um ID exclusivo (UID) baseado em sha256 criado com a consulta, parâmetros, métodos e o tipo de operação.
A biblioteca não faz nenhuma operação de cache diretamente, em vez disso, permite cache os resultados usando uma biblioteca externa.
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) Define o serviço de cache
$ pdoOne = new PdoOne ( " mysql " , " 127.0.0.1 " , " travis " , "" , " travisdb " );
$ cache = new CacheService ();
$ $ pdoOne -> setCacheService ( $ cache );(3) Use o cache da seguinte forma, devemos adicionar o método usecache () em qualquer parte da consulta.
$ 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 ();A sequência é uma alternativa ao campo Auto_numeric (Identity). Possui dois métodos para criar uma sequência: floco de neve e sequência . É uma alternativa criar um GUID principalmente porque retorna um número (um GUID geralmente é uma string que é mais caro indexar e armazenar)
O objetivo da sequência é criar um número único que nunca seja repetido.
$ 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.É possível criar uma nova sequência sem nenhuma tabela. É rápido, mas pode ter problemas de colisões.
Ele garante um número livre de colisão apenas se não fizermos mais de uma operação por 0,0001 segundo , no entanto, também adiciona um número aleatório pseudo (0-4095 com base no tempo), portanto as chances de colisão são 1/4095 (por duas operações realizadas a cada 0,0001 segundo). É baseado no número de floco de neve do Twitter. ou seja. Você está a salvo de colisões se estiver fazendo menos de 1 milhão de operações por segundo (tecnicamente: 45 milhões).
$ pdo-> getSequencephp ([imprevisível = false]) retorna uma sequência sem usar uma tabela. Essa sequência é mais eficiente que $ Dao-> GetSequence, mas usa um valor aleatório para lidar com colisões.
Se o Upredictable é verdadeiro, ele retorna um número imprevisível (ele vira alguns dígitos)
$ 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" | Campo | Descrição | Exemplo |
|---|---|---|
| $ prefixbase | Se precisarmos adicionar um prefixo a cada mesa | $ this-> prefixbase = 'exemplo_'; |
| $ internalcachecounter | O balcão de acertos do cache interno. | $ this-> internalcachecounter =; |
| $ nodeid | Usado por sequência (floco de neve). Nodeid É o identificador do nó. Deve estar entre 0..1023 | $ this-> nodeId = 3; |
| $ tablesequence | O nome da sequência da tabela (floco de neve) | $ this-> tablesequence = "tableseq1"; |
| $ Masks0 | Se queremos gerar um número imprevisível (usado por sequência) | $ this-> Masks0 = [0,1,2,3,4]; |
| $ masks1 | Se queremos gerar um número imprevisível (usado por sequência) | $ this-> Masks1 = [4,3,2,1,0]; |
| $ databaseType | O tipo atual de banco de dados. É definido via El construtor | eco $ this-> databaseType; |
| $ servidor | A máquina de servidor atual | eco $ this-> servidor; |
| $ usuário | O usuário atual | eco $ this-> usuário; |
| $ PWD | A senha atual | eco $ this-> pwd; |
| $ db | O banco de dados atual ou esquema (Oracle ignora esse valor) | eco $ this-> dB; |
| $ charset | Para definir o charset padrão. Deve ser definido via construtor | eco $ this-> charset; |
| $ isopen | É verdade se o banco de dados estiver conectado de outra forma, é falso | if ($ this-> isopen) {…}; |
| $ wlowronerror | Se true (padrão), ele lança um erro se acontecer um erro. Se falso, então a execução continua | $ this-> tloNenerror = false; |
| $ conn1 | A instância do PDO. Você pode defini -lo ou usá -lo diretamente. | $ this-> conn1-> pdostatement (..); |
| $ transactionOpen | Verdadeiro se a transação estiver aberta | if ($ this-> transactionOpen) {…}; |
| $ readonly | Se o banco de dados estiver no modo somente leitura ou não. Se verdadeiro, devemos evitar escrever no banco de dados | $ this-> readonly = true; |
| $ logfile | Nome do arquivo completo do arquivo de log. Se estiver vazio, não armazena um arquivo de log. O arquivo de log é limitado a 1 MB | $ this-> logfile = "/pasta/file.log"; |
| $ errortext | Ele armazena o último erro. Runget e BEGN RESERVES | echo $ this-> errortext; |
| $ isthrow | pendência | $ this-> iswrow =; |
| $ loglevel | Indica o nível atual de log. 0 = sem log (para produção), 3 = log completo | $ this-> loglevel = 3; |
| $ lastQuery | Última consulta executada | eco $ this-> lastQuery; |
| $ lastParam | Os últimos parâmetros. É uma matriz associativa | eco $ this-> lastParam; |
Esta biblioteca permite a criptografia/descriptografia das informações.
Para definir a criptografia, você pode usar o próximo comando:
$ 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.Então você pode criptografar e descriptografar um valor usando
$ encrypted = $ this -> encrypt ( $ original ); // encrypt $original
$ original = $ this -> decrypt ( $ encrypted ); // decrypt $encryptedExemplo:
$ 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. Você pode definir o nível de log como 3. O nível de log funciona quando a operação falhar, quanto maior o nível de log, mostra a maioria das informações.
$ pdoOne -> logLevel = 3 ; // the highest for debug.Por padrão, o Pdoone lança erros de PHP, mas poderíamos evitá -lo definindo o campo $ wlowronerror como 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.Se vazio, ele não gerará um arquivo de log (usando o arquivo de log PHP)
$ pdoOne -> logFile = true ; O Pdoone tem alguns recursos disponíveis apenas na CLI.

Execute a próxima linha (na pasta Lib)
PHP PDOONECLI.PHP
(ou apontando para a pasta direita)
php/var/web/fornecedor/eftec/lib/pdoonecli
Você pode usar o sinalizador "-i" para inserir no modo interativo.
Você pode usar a tecla TAB para valores de preenchimento automático (se houver).

Nota: Você também pode salvar e carregar a configuração.
Conecte -se ao MySQL e gerar um CSV da tabela "ator"
# # 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 csvSalve a configuração em um arquivo
php pdoonecli --databasetype mysql --server 127.0.0.1 -u root -p abc.123 --database sakila --saveconfig myconfigCarregue a configuração de um arquivo
php pdoonecli --loadconfig myconfig -in actor -out csvVocê pode usar a bandeira "-cli" para gerar as classes do repositório

A CLI é interativa e permite carregar e salvar a configuração.
A funcionalidade gerará uma classe de repositório pronta para uso.
Digamos o próximo exemplo
mysql:
php pdoone.php -database mysql - -server 127.0.0.1:3306 --User raiz -p abc.123 -db sakila -input "ator" -outcode
SQLSRV:
php pdoone.php -database sqlsrv -server pcjc sqlexpress --user sa -p abc.123 -db sakila -input "ator" -outcode de classe
Ele se conectará ao banco de dados MySQL, IP: 127.0.0.1 e banco de dados Sakila, e lerá a tabela "ator".
Ele retornará o próximo resultado
/**
* 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
}
// .....
}Essa funcionalidade gerará uma nova classe de repositório com as operações mais comuns: inserir, listar, atualizar, excluir, obter, contar, criar tabela, soltar tabela e tabela truncada
Por que precisamos gerar uma aula? (em vez de herdar um) Esta classe CRUD é apenas um ponto de partida. O desenvolvedor pode modificar o código, adicionar novos métodos, modificar o método anterior e assim por diante.
Para usar a classe, poderíamos escrever o próximo código:
// 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.Como alternativa, você pode gerar o arquivo php automaticamente da seguinte maneira:
php pdoone.php -database mysql -server 127.0.0.1:3306 -User raiz -pwd abc.123 -db sakila -input "ator" -Output ClassCode> atorRepo.php
NOTA: O código não tem tags, namespace e uso de php, mas tudo o mais está aqui.
Será necessário uma consulta e retornará um código PHP com a consulta formatada.
Exemplo:
php pdoone.php -database mysql -server 127.0.0.1:3306 -User raiz -pwd abc.123 -db sakila -input "selecione * do ator" -Output SelectCode
Ele gerará o próximo código:
/** @var array $result=array(["actor_id"=>0,"first_name"=>'',"last_name"=>'',"last_update"=>'']) */
$ result = $ pdo
-> select ( " * " )
-> from ( " actor " )
-> toList ();Ele gerará uma matriz associativa (com valores padrão) baseada na consulta ou na tabela selecionada.
php pdoone.php -database mysql -server 127.0.0.1:3306 -User raiz -pwd abc.123 -db sakila -input "selecione * do ator" -Output ArrayCode
Vai retornar:
// ["actor_id"=>0,"first_name"=>'',"last_name"=>'',"last_update"=>'']Ele retornará o resultado da consulta como um JSON
php pdoone.php -database mysql -server 127.0.0.1:3306 -User raiz -pwd abc.123 -db sakila -input "selecione * do ator" -Output json
Vai retornar:
[{ "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 " }]Ele retornará o resultado da consulta como um JSON
php pdoone.php -database mysql -server 127.0.0.1:3306 -User raiz -pwd abc.123 -db sakila -input "selecione * do ator" -Output csv
Vai retornar:
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"
Alternativamente à CLI, a biblioteca tem um visual de interface. Faz toda a operação da CLI.

Basta chamar o método 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 ();Há um exemplo nos exemplos de pasta/testui.php
Os próximos comandos geralmente são executados sozinhos (não em uma cadeia de métodos)
| Método | Descrição | Exemplo |
|---|---|---|
| createTable () | Cria a tabela e os índices usando a definição dentro do repo | TablaparentRepo :: createTable (); |
| CreateForeignKeys () | Crie todas as chaves estrangeiras da tabela | TablaparentRepo :: createforeignKeys (); |
| DropTable () | Solte a mesa | TablaparentRepo :: DropTable (); |
| truncar() | Truncar a tabela | TablaparentRepo :: truncate (); |
| validTable () | Validar se a tabela não mudou | $ ok = tablaParentRepo :: 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 clasOs operadores aninhados são métodos que devem estar entre nossa cadeia de métodos.
ClassRepo :: op () :: where () :: finalop () é ✅
ClassRepo :: op () :: op () :: where () deixará a corrente aberta
Por exemplo:
// 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| Método | Descrição | Exemplo |
|---|---|---|
| onde() | Adiciona um onde à corrente | Tablaparentrepo :: where () |
| ordem() | Adiciona um pedido à cadeia | Tablaparentrepo :: order () |
| grupo() | adiciona um grupo à cadeia | Tablaparentrepo :: Grupo () |
| limite() | Limita os resultados | Tablaparentrepo :: limite () |
| página() | É semelhante ao limite, mas usa a página | Tablaparentrepo :: página () |
| Innerjoin () | Adiciona uma junção interna à consulta | Tablaparentrepo :: innerjoin () |
| esquerda() | Adiciona uma junção esquerda à consulta | Tablaparentrepo :: esquerda () |
| certo() | Adiciona uma junção certa à consulta | Tablaparentrepo :: certo () |
Temos métodos diferentes para gerar um comando DQL (consulta) em nosso banco de dados.
Se a operação falhar, eles retornam um falso e podem desencadear uma exceção.
Os próximos métodos devem estar no final da cadeia. Exemplos:
ClassRepo :: op () :: op () :: tolist () é ✅
ClassRepo :: op () :: tolist () :: op () acionará uma exceção
| Comando | Descrição | Exemplo |
|---|---|---|
| tolista () | Retorna uma variedade de elementos | $ data = tablenamerepo :: tolist (); // selecione * do tableRepo $ data = tablenamerepo :: where ('a1 =?', [$ value]) :: tolist (); // Selecione * no tableRepo onde a1 = $ valor |
| primeiro() | Retorna uma linha simples | $ data = tablenamerepo :: primeiro ($ pk); // Selecione * no tablerepo onde pk = $ pk (ele sempre retorna 1 ou zero valores) $ data = tablenamerepo :: where ('a1 =?', [$ value]) :: primeiro (); // retorna o primeiro valor (ou falso se não for encontrado) |
| existe () | Retorna true se houver uma chave primária | $ data = tablenamerepo :: exist ($ pk); // retorna true se o objeto existir. |
| contar() | Retorna o número de linhas em uma consulta | $ data = tablenamerepo :: count ($ condições); $ data = tablenamerepo :: where ('a1 =?', [$ value]) :: count (); |
Os próximos métodos permitem inserção, atualização ou exclusão de valores no banco de dados.
| Método | Descrição | Exemplo |
|---|---|---|
| inserir | Ele insere um valor no banco de dados. Poderia retornar uma identidade | $ identity = tablaParentRepo :: insert ($ obj); |
| atualizar | Ele atualiza um valor no banco de dados. | Tablaparentrepo :: update ($ obj); |
| excluir | Ele exclui um valor do banco de dados. | TablaParentRepo :: delete ($ obj); |
| DeletebyId | Ele exclui um valor (usando a chave primária como condição) do banco de dados. | TablaparentRepo :: 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);É possível validar o modelo. O modelo é validado usando as informações do banco de dados, usando o tipo de coluna, o comprimento, se o valor permitir nulo e se for identidade (Auto Numeric).
$ obj =[ ' IdUser ' => 1 , ' Name ' ='John Doe'];
UserRepo:: validateModel ( $ obj , false ,[ ' _messages ' ]); // returns true if $obj is a valid User.Uma matriz recursiva é uma variedade de cordas com valores que poderiam ser lidos ou obtidos ou comparados. Por exemplo, para participar de uma tabela condicionalmente. O PdoOne não o usa diretamente, mas o _basepdooneRepo o usa (_basepdooneRepo é uma classe usada quando geramos uma classe de serviço de repositório automaticamente).
Exemplo
$ 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. Ele define uma matriz recursiva.
Este valor é redefinido cada vez que os métodos de cadeia termina.
Ele recebe a matriz recursiva.
Ele retorna verdadeiro se recursivo tiver alguma agulha.
Se $ this-> recursivo for ['*'], ele sempre retorna true.
$ this -> select ( ' * ' )-> from ( ' table ' )-> recursive ([ ' * ' ]);
$ this -> hasRecursive ( ' anything ' ); // it always returns true. | Biblioteca | Inserir | FINDPK | hidrato | com | tempo |
|---|---|---|---|---|---|
| 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 |
| Yii2mscalar -hidrato | 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 |
| Doutrinem | 2119 | 250 | 1592 | 1258 | 18.139 |
| DoutrineMwithCache | 2084 | 243 | 1634 | 1155 | 17.952 |
| DoutrinoMarrayHydrate | 2137 | 240 | 1230 | 877 | 16,83 |
| Doutrinemscalar -hidrato | 2084 | 392 | 1542 | 939 | 18.887 |
| DoutrinemWithoutProxies | 2119 | 252 | 1432 | 1960 | 19.822 |
| Eloquente | 3691 | 228 | 708 | 1413 | 12.155 |
O Pdoone adiciona um pouco de Ovehead sobre o PDO, no entanto, é simples um invólucro ao PDO.
Isso significa que você é atualizado PdoOne e está usando uma classe gerada pelo ORM. Esta classe deve ser re-gerada.
Em poucas palavras:
Toda versão principal significa que pode quebrar o código antigo. Ou seja, 1.0 -> 2.0
Cada versão menor significa que adiciona uma nova funcionalidade, isto é, 1.5 -> 1.6 (novos métodos)
Cada versão decimal significa que corrige/corrige/refatorando uma funcionalidade anterior IE 1.5.0 -> 1.5.1 (correção)
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'); // agora
[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