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主要是过程式编程,但也支持面向对象编程(OOP);Python支持多种范式,包括OOP、函数式和过程式编程。PHP适合web开发,Python适用于多种应用,如数据分析和机器学习。

PHP起源于1994年,由RasmusLerdorf开发,最初用于跟踪网站访问者,逐渐演变为服务器端脚本语言,广泛应用于网页开发。Python由GuidovanRossum于1980年代末开发,1991年首次发布,强调代码可读性和简洁性,适用于科学计算、数据分析等领域。

PHP适合网页开发和快速原型开发,Python适用于数据科学和机器学习。1.PHP用于动态网页开发,语法简单,适合快速开发。2.Python语法简洁,适用于多领域,库生态系统强大。

PHP在现代化进程中仍然重要,因为它支持大量网站和应用,并通过框架适应开发需求。1.PHP7提升了性能并引入了新功能。2.现代框架如Laravel、Symfony和CodeIgniter简化开发,提高代码质量。3.性能优化和最佳实践进一步提升应用效率。

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP类型提示提升代码质量和可读性。1)标量类型提示:自PHP7.0起,允许在函数参数中指定基本数据类型,如int、float等。2)返回类型提示:确保函数返回值类型的一致性。3)联合类型提示:自PHP8.0起,允许在函数参数或返回值中指定多个类型。4)可空类型提示:允许包含null值,处理可能返回空值的函数。

PHP中使用clone关键字创建对象副本,并通过\_\_clone魔法方法定制克隆行为。1.使用clone关键字进行浅拷贝,克隆对象的属性但不克隆对象属性内的对象。2.通过\_\_clone方法可以深拷贝嵌套对象,避免浅拷贝问题。3.注意避免克隆中的循环引用和性能问题,优化克隆操作以提高效率。

PHP适用于Web开发和内容管理系统,Python适合数据科学、机器学习和自动化脚本。1.PHP在构建快速、可扩展的网站和应用程序方面表现出色,常用于WordPress等CMS。2.Python在数据科学和机器学习领域表现卓越,拥有丰富的库如NumPy和TensorFlow。


热AI工具

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

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

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

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

热门文章

热工具

WebStorm Mac版
好用的JavaScript开发工具

SublimeText3 Linux新版
SublimeText3 Linux最新版

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

SublimeText3 英文版
推荐:为Win版本,支持代码提示!

适用于 Eclipse 的 SAP NetWeaver 服务器适配器
将Eclipse与SAP NetWeaver应用服务器集成。