MongoDB 提供了包括 PHP 在内的各种语言的驱动程序。为了简化在 PHP 中创建聚合管道的过程,我们需要将所有阶段和运算符建模为可以组合的函数。
聚合管道是“阶段”文档的列表。我们将举一个使用 进行查询$match和连接的示例$lookup:
db.orders.aggregate([ { $match: { $or: [ { status: "shipped" }, { created_at: { $gte: ISODate("2023-01-01T00:00:00Z") } } ] } }, { $lookup: { from: "inventory", localField: "product_id", foreignField: "product_id", as: "inventory_docs" } } ])
每个带有美元前缀的键都是我们要为其提供工厂方法的运算符。
命名空间函数
最明显的解决方案是创建命名空间函数,例如:MongoDBOperatoreqof$eq运算符。
namespace MongoDB\Operator; function eq(mixed $value): array { return ['$eq' => $value]; } function lookup(string $from, string $localField, string $foreignField, string $as): array { return ['$lookup' => [ 'from' => $from, 'localField' => $localField, 'foreignField' => $foreignField, 'as' => $as, ]]; }
使用带有命名参数的函数,管道将用 PHP 编写:
pipeline( match( or( query(status: eq('shipped')), query(date: gte(new UTCDateTime())), ), ), lookup(from: 'inventory', localField: 'product_id', foreignField: 'product_id', as: 'inventory_docs'), );
但是,某些运算符名称与PHP 中的保留关键字冲突。我们不能创建具有以下名称的函数(全局或命名空间):
and,
or,
match,
unset,
set,
为函数名添加后缀
为了避免保留名称的问题,我们可以在函数名称中添加前缀或后缀。
以运算符类型作为后缀:
function andQuery(...) { /* ... */ } function matchStage(...) { /* ... */ }
带下划线:
function _and(...) { /* ... */ } function _match(...) { /* ... */ }
或者使用表情符号。漂亮,但不实用:
function ?and(...) { /* ... */ } function ?match(...) { /* ... */ }
静态类方法
碰巧的是,方法名称的保留关键字列表较短。我们可以在类上创建静态方法。
final class Stage { public static function lookup(...) { /* ... */ } public static function match(...) { /* ... */ } } final class Query { public static function and(...) { /* ... */ } public static function eq(...) { /* ... */ } }
字写得有点长了,不过还是可读的。
new Pipeline( Stage::match( Query::or( Query::query(status: Query::eq('shipped')), Query::query(date: Query::gte(new UTCDateTime())), ), ), Stage::lookup(from: 'inventory', localField: 'product_id', foreignField: 'product_id', as: 'inventory_docs'), );
为了防止任何人创建此类的实例,我们可以将构造函数设为私有。
final class Operator { // ... private function __construct() {} // This constructor cannot be called }
我们也可以使用enum不带外壳的。Enum 接受静态方法并且不能实例化。
enum Query { public static function and() { /* ... */ } public static function eq() { /* ... */ } }
类和枚举静态方法都可以以相同的方式调用。
变量中的闭包
由于找不到理想的解决方案,我们开始热衷于不太可能的解决方案。
如果我们想要一个看起来与 MongoDB 语法非常相似且没有名称限制的简短语法,那么我们就会想到使用变量来存储闭包。请注意,这(...)是PHP 8.1 中创建闭包的新语法。
$eq = Operator::eq(...); $and = Operator::and(...);
$PHP 使用美元符号作为变量前缀,MongoDB 使用相同的运算符作为前缀。
pipeline( $match( $or( $query(status: $eq('shipped')), $query(date: $gte(new UTCDateTime())), ), ), $lookup(from: 'inventory', localField: 'product_id', foreignField: 'product_id', as: 'inventory_docs'), );
库可以将这些闭包作为数组提供。
enum Query { public static function and(array ...$queries) { /* ... */ } public static function eq(mixed $value) { /* ... */ } public static function query(mixed ...$query) { /* ... */ } /** @return array{and:callable,eq:callable,query:callable} */ public static function functions(): array { return [ 'and' => self::and(...), 'eq' => self::eq(...), 'query' => self::query(...), ]; } }
获取所有变量的语法有点冗长,但仍然可读。
['and' => $and, 'eq' => $eq, 'query' => $query] = Query::functions();
extract我们可以使用 Laravel 中经常使用但 PHPStorm 和静态分析工具非常讨厌的神奇功能将所有变量导入到当前作用域中。
extract(Query::functions()); var_dump($and( $query(foo: $eq(5)), $query(bar: $eq(10)) )); // INFO: MixedFunctionCall - Cannot call function on mixed
结论
正如您所看到的,在使用保留关键字时,PHP 中的函数命名并不那么简单。
以上是如何克服PHP的命名限制来建模MongoDB运算符的详细内容。更多信息请关注PHP中文网其他相关文章!

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

在php中,可以使用substr()函数来读取字符串后几个字符,只需要将该函数的第二个参数设置为负值,第三个参数省略即可;语法为“substr(字符串,-n)”,表示读取从字符串结尾处向前数第n个字符开始,直到字符串结尾的全部字符。

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

方法:1、用“str_replace(" ","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\ \;||\xc2\xa0)/","其他字符",$str)”语句。

查找方法:1、用strpos(),语法“strpos("字符串值","查找子串")+1”;2、用stripos(),语法“strpos("字符串值","查找子串")+1”。因为字符串是从0开始计数的,因此两个函数获取的位置需要进行加1处理。


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

Atom编辑器mac版下载
最流行的的开源编辑器

Dreamweaver CS6
视觉化网页开发工具

Dreamweaver Mac版
视觉化网页开发工具

记事本++7.3.1
好用且免费的代码编辑器

MinGW - 适用于 Windows 的极简 GNU
这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。