Класс, упрощающий работу с подключениями к базе данных. Универсальная взаимозаменяемая CRUD- система.
Это версия 5 , которая сломает пользователей версии 4 .
В основном за счет:
Использование namespace
в файле ezFunctions.php global
функций. Использование глобальных функций потребует от пользователя начать файл .php
примерно так:
use function ezsql functions where ;
// Or
use function ezsql functions {
getInstance ,
selecting ,
inserting ,
};
Свойства класса, которые были доступны с помощью магических методов get/set
, теперь PSR 1 CamelCase.
select
ez_mysqli
переименован в dbSelect
.
Переименован метод класса и поведение selecting
для select
.
selecting
и новые методы inserting
можно вызывать без имени таблицы, только другие необходимые параметры:
tableSetup(name, prefix), or setTable(name), setPrefix(append)
, при вызове без предварительной настройки возвращается false
.ing
. Удалены глобальные функции, в которых передается имя table
. Используйте функции, использующие предустановленные имена таблиц, оканчивающиеся на ing
.
переименовал cleanInput в clean_string
переименовал createCertificate в create_certificate
добавлен глобальный get_results для возврата наборов результатов в разных форматах
Версия 4 содержит множество современных практик программирования, которые могут сломать пользователей версии 3.
Версия 3 сломала версию 2.1.7 в одном важном аспекте: для нее требовался PHP 5.6 . При этом поддержка расширений MySQL прекращена, кроме этого, в использовании библиотеки ничего не изменилось, только дополнительные функции.
В этой библиотеке есть класс Database
, представляющий собой комбинацию шаблона Factory с размещением контейнера внедрения зависимостей. Эта библиотека теперь следует многим принципам ООП, один из которых заключается в том, что публичный доступ к свойствам методов был удален. Эта библиотека также соответствует соглашениям PSR-2, PSR-4, PSR-11 и, в основном, PSR-1, работа над которой все еще продолжается.
Полный обзор см. в документации Wiki, которая еще не полностью завершена.
composer require ezsql/ezsql
require ' vendor/autoload.php ' ;
// **** is one of mysqli, pgsql, sqlsrv, sqlite3, or Pdo.
use ezsql Database ;
$ db = Database:: initialize ( ' **** ' , [ $ dsn_path_user , $ password , $ database , $ other_settings ], $ optional_tag );
// Is same as:
use ezsql Config ;
use ezsql Database ez_ ****;
$ settings = new Config ( ' **** ' , [ $ dsn_path_user , $ password , $ database , $ other_settings ]);
$ db = new ez_ ****( $ settings );
Эта библиотека предполагает, что разработчик использует какую-то IDE с включенным Intellisense. В области комментариев/док-блока будет храниться недостающая документация. Дополнительные примеры см. в тестах phpunit . Тесты представляют собой полнофункциональные интеграционные тесты, то есть это тесты в реальном времени, а не макеты.
Следующее было добавлено начиная с версии 2.1.7.
Общие методы
to_string($arrays, $separation = ',');
clean($string);
create_cache(string $path = null);
secureSetup(string $key = 'certificate.key',
string $cert = 'certificate.crt',
string $ca = 'cacert.pem',
string $path = '.'._DS
);
secureReset();
create_certificate(string $privatekeyFile = certificate.key,
string $certificateFile = certificate.crt,
string $signingFile = certificate.csr,
string $ssl_path = null, array $details = [commonName => localhost]
);
Методы таблицы ярлыков
create(string $table = null, ...$schemas);// $schemas requires... column()
column(string $column = null, string $type = null, ...$args);
primary(string $primaryName, ...$primaryKeys);
index(string $indexName, ...$indexKeys);
drop(string $table);
Пример
// Creates an database table
create ( ' profile ' ,
// and with database column name, datatype
// data types are global CONSTANTS
// SEQUENCE|AUTO is placeholder tag, to be replaced with the proper SQL drivers auto number sequencer word.
column ( ' id ' , INTR , 11 , AUTO , PRIMARY ), // mysqli
column ( ' name ' , VARCHAR , 50 , notNULL),
column ( ' email ' , CHAR , 25 , NULLS ),
column ( ' phone ' , TINYINT )
);
innerJoin(string $leftTable = null, string $rightTable = null,
string $leftColumn = null, string $rightColumn = null, string $tableAs = null, $condition = EQ);
leftJoin(string $leftTable = null, string $rightTable = null,
string $leftColumn = null, string $rightColumn = null, string $tableAs = null, $condition = EQ);
rightJoin(string $leftTable = null, string $rightTable = null,
string $leftColumn = null, string $rightColumn = null, string $tableAs = null, $condition = EQ);
fullJoin(string $leftTable = null, string $rightTable = null,
string $leftColumn = null, string $rightColumn = null, string $tableAs = null, $condition = EQ);
prepareOn (); // When activated will use prepare statements for all shortcut SQL Methods calls.
prepareOff (); // When off shortcut SQL Methods calls will use vendors escape routine instead. This is the default behavior.
having(...$having);
groupBy($groupBy);
union(string $table = null, $columnFields = '*', ...$conditions);
unionAll(string $table = null, $columnFields = '*', ...$conditions);
orderBy($orderBy, $order);
limit($numberOf, $offset = null)
where( ...$whereConditions);
select(string $table = null, $columnFields = '*', ...$conditions);
create_select(string $newTable, $fromColumns, $oldTable = null, ...$conditions);
select_into(string $newTable, $fromColumns, $oldTable = null, ...$conditions);
update(string $table = null, $keyAndValue, ...$whereConditions);
delete(string $table = null, ...$whereConditions);
replace(string $table = null, $keyAndValue);
insert(string $table = null, $keyAndValue);
create(string $table = null, ...$schemas);
drop(string $table = null);
alter(string $table = null, ...$alteringSchema);
insert_select(string $toTable = null, $toColumns = '*', $fromTable = null, $fromColumns = '*', ...$conditions);
// The variadic ...$whereConditions, and ...$conditions parameters,
// represent the following global functions.
// They are comparison expressions returning an array with the given arguments,
// the last arguments of _AND, _OR, _NOT, _andNOT will combine expressions
eq ( ' column ' , $ value , _AND ), // combine next expression
neq ( ' column ' , $ value , _OR ), // will combine next expression again
ne ( ' column ' , $ value ), // the default is _AND so will combine next expression
lt ( ' column ' , $ value )
lte ( ' column ' , $ value )
gt ( ' column ' , $ value )
gte ( ' column ' , $ value )
isNull ( ' column ' )
isNotNull ( ' column ' )
like ( ' column ' , ' _%? ' )
notLike ( ' column ' , ' _%? ' )
in ( ' column ' , ... $ value )
notIn ( ' column ' , ... $ value )
between ( ' column ' , $ value , $ value2 )
notBetween ( ' column ' , $ value , $ value2 )
// The above should be used within the where( ...$whereConditions) clause
// $value will protected by either using escape or prepare statement
// To allow simple grouping of basic $whereConditions,
// wrap the following around a group of the above comparison
// expressions within the where( ...$whereConditions) clause
grouping ( eq (key, value, combiner ), eq (key, value, combiner ) )
// The above will wrap beginning and end grouping in a where statement
// where required to break down your where clause.
// Note: The usage of this method will require the user/developer to check
// if `query_string` or `param_array` is valid.
//
// This is really an `private` internal method for other shortcut methods,
// it's made public for `class development` usage only.
//
//
// Supply the the whole `query` string, and placing '?' within, with the same number of arguments in an array.
// It will then determine arguments type, execute, and return results.
query_prepared (string $ query_string , array $ param_array );
// You will need to call this method to get last successful query result.
// It wll return an object array.
queryResult ();
// To get all shortcut SQL methods calls to use prepare statements
$ db -> prepareOn (); // This needs to be called at least once at instance creation
$ values = [];
$ values [ ' name ' ] = $ user ;
$ values [ ' email ' ] = $ address ;
$ values [ ' phone ' ] = $ number ;
$ db -> insert ( ' profile ' , $ values );
$ db -> insert ( ' profile ' , [ ' name ' => ' john john ' , ' email ' => ' john@email ' , ' phone ' => 123456 ]);
// returns result set given the table name, column fields, and ...conditions
$ result = $ db -> select ( ' profile ' , ' phone ' , eq ( ' email ' , $ email ), between ( ' id ' , 1 , $ values ));
foreach ( $ result as $ row ) {
echo $ row -> phone ;
}
$ result = $ db -> select ( ' profile ' , ' name, email ' ,
// Conditionals can also be called, stacked with other functions like:
// innerJoin(), leftJoin(), rightJoin(), fullJoin()
// as (leftTable, rightTable, leftColumn, rightColumn, tableAs, equal condition),
// where( eq( columns, values, _AND ), like( columns, _d ) ),
// groupBy( columns ),
// having( between( columns, values1, values2 ) ),
// orderBy( columns, desc ),
// limit( numberOfRecords, offset ),
// union(table, columnFields, conditions),
// unionAll(table, columnFields, conditions)
$ db -> where ( eq ( ' phone ' , $ number , _OR ), neq ( ' id ' , 5 ) ),
// another way: where( array(key, operator, value, combine, combineShifted) );
// or as strings double spaced: where( "key operator value combine combineShifted" );
$ db -> orderBy ( ' name ' ),
$ db -> limit ( 1 )
);
foreach ( $ result as $ row ) {
echo $ row -> name . ' ' . $ row -> email ;
}
// To get results in `JSON` format
$ json = get_results ( JSON , $ db );
$ db -> query_prepared ( ' INSERT INTO profile( name, email, phone) VALUES( ?, ?, ? ); ' , [ $ user , $ address , $ number ]);
$ db -> query_prepared ( ' SELECT name, email FROM profile WHERE phone = ? OR id != ? ' , [ $ number , 5 ]);
$ result = $ db -> queryResult (); // the last query that has results are stored in `lastResult` protected property
// Or for results in other formats use the global function, will use global database instance if no `$db` supplied
$ result = get_results ( / * OBJECT | ARRAY _ A | ARRAY _ N | JSON */ , $ db ); // Defaults to `OBJECT`
foreach ( $ result as $ row ) {
echo $ row -> name . ' ' . $ row -> email ;
}
Большинству методов быстрого доступа доступны глобальные функции счетчика. Доступ к ним можно получить, только начав ваш файл .php
следующим образом:
use function ezsql functions functionBelow ;
// Or as here, a complete list.
use function ezsql functions {
database ,
mysqlInstance ,
pgsqlInstance ,
mssqlInstance ,
sqliteInstance ,
pdoInstance ,
tagInstance ,
setInstance ,
getInstance ,
clearInstance ,
get_vendor ,
///
to_string ,
clean_string ,
is_traversal ,
sanitize_path ,
create_certificate ,
///
column ,
primary ,
foreign ,
unique ,
index ,
addColumn ,
dropColumn ,
changingColumn ,
///
eq ,
neq ,
ne ,
lt ,
lte ,
gt ,
gte ,
isNull ,
isNotNull ,
like ,
in ,
notLike ,
notIn ,
between ,
notBetween ,
///
where ,
grouping ,
groupBy ,
having ,
orderBy ,
limit ,
innerJoin ,
leftJoin ,
rightJoin ,
fullJoin ,
union ,
unionAll ,
///
creating ,
deleting ,
dropping ,
replacing ,
selecting ,
inserting ,
altering ,
get_results ,
table_setup ,
set_table ,
set_prefix ,
select_into ,
insert_select ,
create_select ,
};
Для использования/документации функций см. ezFunctions.php.
Вклады поощряются и приветствуются; Я всегда рад получить отзывы или запросы на включение на Github :) Создавайте проблемы Github для ошибок и новых функций и комментируйте те, которые вас интересуют.
ezsql — это программное обеспечение с открытым исходным кодом, первоначально лицензированное под лицензией (LGPL-3.0), а дополнительные части — под лицензией (MIT).