imrgrgs / php-utils
Requires
- php: >=5.6
This package is auto-updated.
Last update: 2024-09-26 02:42:50 UTC
README
一个简单的php库
名称: php-utils
许可: MIT
作者: imrgrgs
版本: 1.0.19
需求: PHP >= 5.6, PDO
关于php-utils
php-utils是一个微型ORM,既是一个流畅的查询API,也是一个CRUD模型类。
php-utils建立在PDO之上,非常适合小型到中型项目,这些项目更注重简单性和快速开发,而不是无限的可扩展性和功能。php-utils易于处理表关系,并提供获取SQL的API。
特性
- PDO和预编译语句
- 流畅查询
- 关系
- 连接
- 聚合
- 查询调试器和查询分析器
- 活动记录模式
需求
- PHP >= 5.6
- PDO
错误报告
php-utils不会升级错误。不存在的表产生SQL错误,由PDO按照PDO::ATTR_ERRMODE报告。不存在的列产生与尝试访问数组中不存在的键相同的E_NOTICE错误。
它不做的事情。
安装php-utils
您可以直接下载php-utils,或者使用Composer。
要使用Composer安装,请在您的composer.json文件中的require键添加以下内容
"imrgrgs/php-utils": "dev-master"
composer.json
{
"name": "bit-io/myapp",
"description": "My awesome Bio App",
"require": {
"imrgrgs/php-utils": "dev-master"
}
}
使用php-utils
new php-utils( PDO $pdo )
要开始使用php-utils,您必须设置PDO连接。我们将使用变量$DB作为数据库连接,$users
作为表,$friends
作为本教程中另一个表
$pdo = new PDO("mysql:host=localhost;dbname=$dbname", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$DB = new php-utils($pdo);
php-utils php-utils::table( string $tablename )
通过调用方法php-utils::table()
可以直接连接到表
$users = $DB->table('users');
您也可以通过调用表作为方法来设置表。上面也可以这样写
$users = $DB->users();
$friends = $DB->friends();
从那里,您将能够使用php-utils流畅查询接口对表进行任何CRUD操作
##数据修改
php-utils支持数据修改(插入、更新和删除)。php-utils不会执行数据验证,但所有数据库错误都会通过标准的PDO错误报告。对于数据验证,我们认为在数据库级别或应用级别进行验证是最好的
mixed php-utils::insert( Array $data )
要向表中插入数据,请使用insert(Array $data)
,其中$data
可以是单维数组以插入单个条目,也可以是多个数组以进行批量插入。
如果只插入了一行,它将返回创建的对象的活动记录。否则,它将返回插入的总条目数
对于单个条目
$user = $users->insert(array(
"name" => "imrgrgs",
"age" => 30,
"city" => "Charlotte",
"state" => "NC",
"device" => "mobile",
"timestamp" => $DB->NOW()
));
返回此条目的php-utils活动记录实例,您可以使用$user->name
或$user->city
。我们稍后可以做得更多。
对于批量插入
$massInserts = $users->insert(array(
array(
"name" => "imrgrgs",
"city" => "Charlotte",
"state" => "NC",
"device" => "mobile",
"timestamp" => $DB->NOW()
),
array(
"name" => "Cesar",
"city" => "Atlanta",
"state" => "GA",
"device" => "mobile",
"timestamp" => $DB->NOW()
),
array(
"name" => "Gaga",
"city" => "Port-au-Prince",
"state" => "HT",
"device" => "computer",
"timestamp" => $DB->NOW()
),
));
返回插入的总条目数
mixed php-utils::update( Array $data)
在php-utils中更新条目有两种方法,1)通过使用已检索行的活动记录模式,或2)通过使用WHERE查询来指定更新位置。此外,方法php-utils::set($key, $value)
也可以用于在更新之前设置数据。
对于单个条目
$user->update(array(
"city" => "Raleigh"
));
与以下相同
$user->city = "Raleigh";
$user->update();
您也可以使用save()
代替update()
$user->save();
或者使用php-utils::set(Array $data)或php-utils::set($key, $value)
$user->set('city','Raleigh')->update();
对于多个条目
对于多个条目,我们将使用php-utils::set()
和php-utils::where()
来指定更新位置。
php-utils::set(Array $data)
或php-utils::set($key, $value)
对于批量更新,我们将使用set(Array $data)
和where($k, $v)
来设置要更新的数据
$user->set(array(
"country_code" => "US"
))
->where("device", "mobile")
->update();
*在流畅查询接口下还有更多的where
别名
mixed php-utils::save()
Save()
是php-utils::insert()
或php-utils::update()
的快捷方式
插入新数据
$user = $DB->users();
$user->name = "imrgrgs";
$user->city = "Charlotte";
$user->save();
更新
$user = $users->findOne(123456);
$user->city = "Atlanta";
$user->save();
int php-utils::delete()
要删除条目,我们将使用php-utils::delete()
方法
对于单个条目,通过调用delete()
方法将删除当前条目
$user = $users->reset()->findOne(1234);
$user->delete();
对于多个条目,我们将使用php-utils::where()
方法来指定删除位置
$users->where("city", "Charlotte")->delete();
聚合
php-utils为您提供了访问表上聚合方法的方式
int php-utils::count()
根据WHERE子句计数所有条目
$allUsers = $users->count();
$count = $voodorm->where($x, $y)->count();
或对于特定的列名
$count = $users->where($x, $y)->count($columnName);
float php-utils::max( string $columnName )
根据WHERE子句获取$columnName的最大值
$max = $users->where($x, $y)->max($columnName);
float php-utils::min( string $columnName )
根据WHERE子句获取$columnName的最小值
$min = $users->where($x, $y)->min($columnName);
float php-utils::sum( string $columnName )
根据WHERE子句获取$columnName的总和
$sum = $users->where($x, $y)->sum($columnName);
float php-utils::avg( string $columnName )
根据WHERE子句获取$columnName的平均值
$avg = $users->where($x, $y)->avg($columnName);
mixed php-utils::aggregate( string $function )
运行任何聚合函数
$agg = $users->where($x, $y)->aggregate('GROUP_CONCAT $columnName');
查询
php-utils提供了一个流畅的接口,允许您在不编写任何SQL字符的情况下构建简单的查询。
两种方法允许您获取单个条目或多个条目:findOne()
和find()
。以及fromArray()
,将原始数据加载到对象中。
FindOne
php-utils php-utils::findOne()
findOne()
如果找到,则返回单个条目的php-utils
实例,否则将返回FALSE
。
$user = $users->where('id', 1234)
->findOne();
可以在findOne(int $primaryKey)
中设置主键以获取与上述查询相同的结果。这意味着不需要WHERE子句。
$user = $users->findOne(1234);
让我们获取找到的条目
if ($user) {
echo " Hello $user->name!";
// On a retrieved entry you can perform update and delete
$user->last_viewed = $users->NOW();
$suer->save();
}
Find
ArrayIterator php-utils::find()
find()
返回一个找到的行的ArrayIterator
,这些行是php-utils
的实例,否则它将返回False
。
$allUsers = $users->where('gender', 'male')
->find();
foreach ($allUsers as $user) {
echo "{$user->name}";
// On a retrieved entry you can perform update and delete
$user->last_viewed = $users->NOW();
$user->save();
}
find()
在迭代调用时也包含一个快捷方式,例如在foreach中
$allUsers = $users->where('gender', 'male');
foreach ($allUsers as $user) {
echo "{$user->name}";
// On a retrieved entry you can perform update and delete
$user->last_viewed = $users->NOW();
$suer->save();
}
mixed php-utils::find( Closure $callback )
php-utils::find()
也接受一个闭包作为回调来完成您自己的数据操作。执行时,php-utils会将查询中找到的数据传递给闭包函数。
$users->where('gender', 'male');
$results = $users->find(function($data){
$newResults = array();
foreach ($data as $d) {
$d["full_name"] = ucwords("{$data["first_name"]} {$data["last_name"]}");
$newResults[] = $d;
}
return $newResults;
});
FromArray
php-utils php-utils::fromArray( Array $data )
与 find()
和 findOne()
不同,它们会对数据库进行查询以获取数据,而 fromArray()
加载原始数据,并以 php-utils 对象的形式返回。这些数据可能是缓存在 Redis/Memcached 中的,但不是直接来自数据库。
$data = [
"id" => 916,
"name" => "Jose",
"last_name" => "Martinez"
];
$anotherUser = $users->fromArray($data);
现在您可以操作它了
$anotherUse->update(
["name" => "Yolo"]
);
流畅查询构建器
选择
php-utils php-utils::select( $columns = '*' )
用于选择表中的字段。如果省略,php-utils 将获取所有列。
$users->select()
或使用所选列
$users->select("name, age")
->select("last_viewed");
> SELECT name, age, last_viewed
条件
Where
允许您为查询设置条件。下面将找到许多 where
的别名
Where
条件与 php-utils::find()、php-utils::findOne()、php-utils::update() 和 php-utils::delete() 一起使用
重复调用 where
或任何 where
别名将使用 AND 操作符将条件附加到上一个条件。要使用 OR 操作符,必须调用 php-utils::_or()
。更多内容见下文。
php-utils php-utils::where( $condition, $parameters = array() )
这是主要的 where
。它负责所有条件。
$condition
是要使用的条件。它可以包含 ? 或 :name,这通过 PDO 绑定到 $parameters
(因此不需要手动转义)。
$parameters
是绑定到条件的值(值)。它可以是一个数组、一个关联数组或零个或多个标量。
一些示例
$users->where("name", "imrgrgs");
WHERE name = ?
$users->where("age > ?", 25);
WHERE age > ?
$users->where("name in (?, ?, ?)", "Mike", "Jones", "Rich");
WHERE name IN (?, ?, ?)
$users->where("(field1, field2)", array(array(1, 2), array(3, 4)))
WHERE (field1, field2) IN ((?, ?), (?, ?))
但为了便于任务,php-utils 为常见操作提供了一些别名
php-utils php-utils::wherePK( int $primaryKey )
当主键设置为 $users->wherePK(1234);
php-utils php-utils::whereNot( $columnName, $value )
$users->whereNot('age', 24);
WHERE age != ?
php-utils php-utils::whereLike( $columnName, $value )
$users->whereLike('name', 'w%');
WHERE name LIKE ?
php-utils php-utils::whereNotLike( $columnName, $value )
$users->whereNotLike('name', 'r%');
WHERE name NOT LIKE ?
php-utils php-utils::whereGt( $columnName, $value )
$users->whereGt('age', 21);
WHERE age > ?
php-utils php-utils::whereGte( $columnName, $value )
$users->whereGte('age', 21);
WHERE age >= ?
php-utils php-utils::whereLt( $columnName, $value )
$users->whereLt('age', 21);
WHERE age < ?
php-utils php-utils::whereLte( $columnName, $value )
$users->whereLte('age', 21);
WHERE age <= ?
php-utils php-utils::whereIn( $columnName, Array $value )
$users->whereIn('city', array('Charlotte', 'Atlanta'));
WHERE city IN (?,?)
php-utils php-utils::whereNotIn( $columnName, Array $value )
$users->whereNotIn('city', array('Chicago', 'Miami'));
WHERE city NOT IN (?,?)
php-utils php-utils::whereNull( $columnName )
$users->whereNull('city');
WHERE city IS NULL
php-utils php-utils::whereNotNull( $columnName )
$users->whereNotNull('name');
WHERE city NOT NULL
使用 OR 和 AND 的 Where
构建查询时,您可能想在条件中添加 AND 和 OR 操作符。要这样做,请使用与任何 where
别名链接的 php-utils::_and()
和 php-utils::_or()
。
php-utils php-utils::_and()
将 AND
操作符添加到 where 查询中。默认情况下,如果未调用 _and()
,php-utils 将默认添加它。
$users->where("city", "Charlotte")->_and()->whereGte("age", 21);
WHERE city = ? AND age >= ?
php-utils php-utils::_or()
将 OR
操作符添加到 where 查询中。
$users->where("city", "Charlotte")->_or()->whereGte("age", 21)->_or()->where("gender", "female");
WHERE city = ? OR age >= ? OR gender = ?
使用 Wrap() 的 Where
当构建具有多个 Where 组合的复杂查询时,php-utils::wrap()
将 where 组合在一起,用括号括起来。
php-utils php-utils::wrap()
$users->where("city", "Charlotte")->whereGte("age", 21)->wrap()
->where("gender", "female")->where("city", "Atlanta");
WHERE (city = ? AND age >= ?) AND (gender = ? AND city = ?)
php-utils php-utils::wrap()->_and()
wrap()->_and()
使用 AND
操作符与另一个分组 where 执行联合。
$users->where("city", "Charlotte")->whereGte("age", 21)->wrap()->_and()
->where("gender", "female")->where("city", "Atlanta");
WHERE (city = ? AND age >= ?) AND (gender = ? AND city = ?)
php-utils php-utils::wrap()->_or()
wrap()->_or()
使用 OR
操作符与另一个分组 where 执行联合。
$users->where("city", "Charlotte")->whereGte("age", 21)->wrap()->_or()
->where("gender", "female")->where("city", "Atlanta");
WHERE (city = ? AND age >= ?) OR (gender = ? AND city = ?)
同一个查询中的 wrap()->_and() 和 wrap()->_or()
$users->where("id",1)->where("city","charlotte")->wrap()
->where("gender","female")->where("country","US")->wrap()
->_or()->where("city",array("Charlotte","Atlanta"))->wrap()
->_or()->whereLt('age',21)->whereGte("name","imrgrgs")->wrap();
WHERE (id = ? AND city = ?)
AND (gender = ? AND country = ?)
OR ((city IN (?, ?)))
OR (age < ? AND name >= ?)
排序、分组、限制、偏移
php-utils php-utils::orderBy( $columnName, $ordering )
$users->orderBy('name', 'DESC');
ORDER BY name DESC
php-utils php-utils::groupBy( $columnName )
$users->groupBy('city');
GROUP BY city
php-utils php-utils::limit( int $limit )
$users->limit(10);
LIMIT 10
php-utils php-utils::offset( int $offset )
$users->offset(10);
OFFSET 10
连接
php-utils php-utils::join( $tablename, $constraint, $table_alias , $join_operator )
$users->join('friends', 'f.user_id = u.id', 'f')
JOIN friends AS f ON f.user_id = u.id
php-utils php-utils::leftJoin( $tablename, $constraint, $table_alias )
$users->leftJoin('friends', 'f.user_id = u.id', 'f')
LEFT JOIN friends AS f ON f.user_id = u.id
关系
这就是杀手锏!
php-utils的一个杀手级功能是关系。通过将一个表作为对象上的一个方法调用,默认情况下会自动在该引用表上创建一个一对多关系。
为了这个例子,我们将有两个表:user
(id,name,dob)和friend
(id,user_id,friend_id)
friend.user_id
是到user
表的键外键。而friend.friend_id
是朋友的user.id
的外键。
让我们获取所有用户及其朋友
$allUsers = $users->find();
foreach ($allUsers as $user) {
/**
* Connect to the 'friend' table = $user->friend();
* In the back, it does a ONE To MANY relationship
* SELECT * FROM friend WHERE friend.user_id = user.id
*/
$allFriends = $user->friend();
foreach ($allFriends as $friend) {
echo "{$friend->friend_id} : ";
/**
* We got the friend's entry, we want to go back in the user table
* So we link back the friend table to the user table
* SELECT * FROM user WHERE user.id = friend.friend_id LIMIT 1
* It will do a ONE to One relationship
*/
echo $friend->user(["relationship" => biorm\php-utils::HAS_ONE,
"localKey" => "friend_id"
"foreignKey" => "id"])->name;
echo "\n";
}
}
// Same as above but with just one user
$user = $users->findOne($userId);
if($user) {
foreach ($user->friend() as $friend) {
echo "{$friend->friend_id} : ";
echo $friend->user(biorm\php-utils::REL_HASONE, "friend_id")->name;
echo "\n";
}
}
这就是大局。将引用表作为对象上的方法调用将执行关系。
关系:一对多
一对多关系,在我们的用户和朋友的例子中,就是一个用户可以有一个或多个朋友。但每个friend.friend_id
都与一个user.id
关联。这种关系将返回一条或多条记录。
user
(单值)和friend
(多值)之间的关系是一对多关系。
在上面的例子中,我们在朋友的表中执行了一对多关系。
$allFriends = $user->friend();
关系常量
php-utils预定义了常量,允许您选择执行某种关系类型
CONST::HAS_MANY (2)
$allFriends = $user->friend(["relationship" => biorm\php-utils::HAS_MANY]);
这更快。它通过获取所有数据并将数据保留在内存中来进行预加载。它只执行一个查询。默认情况下使用。
关系:一对一
一对一关系在两个方向上都是单值的。在朋友的表中,friend.friend_id
与user.id
相关联
$allFriends = $user->friend();
关系常量
CONST::HAS_ONE (1)
$friendUser = $friend->user(biorm\Core\php-utils::REL_HASONE, "friend_id");
echo $friendUser->name;
它通过获取所有数据并将数据保留在内存中来进行预加载。它只执行一个查询。默认情况下使用。
CONST::REL_LAZYONE (-1)
$friendUser = $friend->user(biorm\php-utils::REL_LAZYONE, "friend_id");
echo $friendUser->name;
这较慢。它通过在请求数据时进行懒加载。它将执行1+N个查询。
关系:多对多
尚未实现。这很复杂......找不到一个适合所有情况的例子......
关系参数
php-utils关系接受4种类型的参数,可以放置在任何位置
$user->friend(NUMBER, STRING, ARRAY, CALLBACK);
数字:通常是关系常量 REL_HASONE = 1
,REL_LAZYONE = -1
,RE_HASMANY = 2
,REL_LAZYMANY = -2
;
$user->friend(biorm\php-utils::REL_HASMANY);
字符串:字符串参数将用作外键名称
$user->friend("friend_id");
数组:数组将用作WHERE条件。数组必须是与表中的字段匹配的键/值匹配
$user->friend(array(
"friendship_start_time >= " => date("Y-m-d")
));
回调:回调是在结果上运行的函数
$user->friend(function($data){
$tableData = array();
foreach($data as $d) {
$tableData[] = array_merge(
$data,
array("visits_count"=>$d[visits_count] + 1)
);
}
return $tableData;
});
现在进行杂烩!
$user->friend(biorm\php-utils::REL_HASONE,
"friend_id",
array("friendship_start_time >= " => date("Y-m-d"),
function($data){
$tableData = array();
foreach($data as $d) {
$tableData[] = array_merge(
$data,
array("visits_count"=>$d[visits_count] + 1)
);
}
return $tableData;
}
));
$user->friend(NUMBER, STRING, ARRAY, CALLBACK);
表结构
表结构允许在数据库中定义表结构。它在构造函数中设置
new php-utils($PDO, $primaryKey = 'id', $foreignKey = '%s_id')
PRIMARYKEY:默认设置为id
,但可以是任何内容
FOREIGNKEY:是外键。默认设置为%s_id,其中%s是表名。因此,在用户表中,在朋友表中外键将是user_id
您还可以使用setStructure($primaryKey, $foreignKey)
来设置结构。
$DB = new php-utils($PDO);
$DB->setStructure("id", "%s_id");
设置表结构很重要,这样php-utils就可以识别关系的主键和外键。
其他方法
以下代码
$users = $DB->table('users');
string php-utils::getPrimaryKeyName()
$users->getPrimaryKeyName();
返回主键名称。大多数情况下它将是 id
字符串 php-utils::getForeignKeyName()
$users->getForeignKeyName();
返回外键名称。基于上述表结构,它将是 user_id
字符串 php-utils::getTableName()
返回表名称
$tableName = $users->getTableName();
php-utils php-utils::tableAlias( string $alias )
将名称设置为表的别名
$users->tableAlias("user");
字符串 php-utils::getTableAlias()
返回表别名名称
$alias = $users->getTableAlias();
数组 php-utils::getStructure()
返回已设置的结构的
$structure = $users->getStructure();
布尔值 php-utils::isSingleRow()
返回一个条目是否为单行的真或假
$user = $users->findOne(123);
if ($user->isSingleRow()) {
// do something here
}
字符串 php-utils::NOW()
它返回当前的DateTime: Y-M-D H:i:s
将php-utils扩展到你的模型中
以下是如何在实际应用程序中设置你的模型与php-utils的示例。我们将设置模型,并使用MVC应用程序的控制器检索它们。该应用程序基于Voodoo,一个PHP的精简模块化MVC框架。
Lib/Model/BaseModel.php
基本模型包含数据库连接,并可以添加额外的方法。BaseModel将在模型类中扩展
<?php
namespace Model;
use biorm;
abstract class BaseModel extends biorm\php-utils
{
private static $pdo = null;
// setup the DB connection
public function __construct()
{
if (! self::$pdo) {
self::$pdo = new PDO("mysql:host=localhost;dbname=$dbname", $username, $password);
self::$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
parent::__construct(self::$pdo);
$instance = parent::table($this->tableName);
$this->table_name = $instance->getTablename();
}
}
Lib/Model/Diskoteka/Artist.php
<?php
namespace Model\Diskoteka;
use Lib\Model;
class Artist extends Model\BaseModel
{
protected $tableName = "artist";
// We concat the first and last name
public function getName()
{
return $this->first_name." ".$this->last_name;
}
}
Lib/Model/Diskoteka/Album.php
<?php
namespace Model\Diskoteka;
use Lib\Model;
class Album extends Model\BaseModel
{
protected $tableName = "album";
// Returns the php-utils object to do more in the query
public function getSongs()
{
return (new Song)->where("album_id", $this->getPK());
}
}
Lib/Model/Diskoteka/Song.php
<?php
namespace Model\Diskoteka;
use Lib\Model,
Closure;
class Song extends Model\BaseModel
{
protected $tableName = "song";
public function getArtistName()
{
return $this->artist_first_name;
}
public function getAlbumTitle()
{
return $this->album_title;
}
// We modify the find() to join this table to album and artist tables
public function find(Closure $callback = null)
{
$this->tableAlias("song")
->select("song.*")
->select("album.title As album_title")
->select("artist.first_name AS artist_first_name")
->leftJoin(new Artist, "artist.id = song.artist_id", "artist")
->leftJoin(new Album, "album.id = song.album_id", "album");
retun parent::find($callback);
}
}
App/Www/Main/Controller/Index.php
使用Voodoo,我们将创建一个控制器来使用模型
<?php
namespace App\Www\Main\Controller;
use Voodoo,
Lib\Model\Diskoteka;
class Index extends Voodoo\Core\Controller
{
/**
* List all songs, which will include the the artist name and album name
* http://the-url/
*/
public function actionIndex()
{
$allSongs = (new Diskoteka\Song);
$allSongs->orderBy("title", "ASC");
$songs = [];
foreach ($allSongs as $song) {
$songs[] = [
"id" => $song->getPK()
"title" => $song->title,
"albumTitle" => $song->getAlbumTitle(),
"artistName" => $song->getArtistName()
];
}
$this->view()->assign("songs", $songs);
}
/**
* Simply get the Artist info
* http://the-url/artist/59
*/
public function actionArtist()
{
$id = $this->getSegment(1); // -> 59
$artist = (new Diskoteka\Artist)->findOne($id);
$countAlbums = (new Diskoteka\Album)
->where("artist_id", $id)
->count();
$this->view()->assign([
"name" => $artist->getName(),
"countAlbums" => $countAlbums
]);
}
/**
* Get the song info, with album basic info
* http://the-url/song/1637
*/
public function actionSong()
{
$id = $this->getSegment(1); // -> 1637
$song = (new Diskoteka\Song)->findOne($id);
if ($song) {
$this->view()->assign([
"id" => $song->getPK()
"title" => $song->title,
"albumTitle" => $song->getAlbumTitle(),
"artistName" => $song->getArtistName()
]);
}
}
/**
* Get the album info including all songs
* http://your-url.com/album/437
*/
public function actionAlbum()
{
$id = $this->getSegment(1);
$album = (new Diskoteka\Album)->findOne($id);
$allSongs = $album->getSongs();
$albumSongs = [];
foreach ($allSongs as $song) {
$albumSongs[] = [
"id" => $song->getPK(),
"title" => $song->title
];
}
$this->view()->assign([
"album" => [
"id" => $album->getPK(),
"title" => $album->title
],
"songs" => $albumSongs
]);
}
}
贡献者
感谢您对php-utils的兴趣。
如果您想做出贡献,请发起一个pull request。
php-utils严格遵守PSR-2
(c) 本年imrgrgs :)