php - 在类内的函数中访问 $bucket 时出现问题
问题描述
我正在尝试构建一个可重用的数据库类,它允许我针对我的沙发数据库访问基本的 crud 功能。当我尝试执行此功能时,我收到以下错误:
PHP Notice: Undefined variable: bucket in
/var/www/html/PHRETS/couchBase.php on line 26 PHP Fatal error:
Uncaught Error: Call to a member function upsert() on null in
/var/www/html/PHRETS/couchBase.php:26 Stack trace:
#0 /var/www/html/PHRETS/retsphp.php(72): couchDb::upsert('OpenHouse::b769...', Object(OpenHouse))
#1 {main} thrown in /var/www/html/PHRETS/couchBase.php on line 26
所以问题是如何从类中的函数访问 $bucket 对象?
这是我在 couchBase.php 中的代码
<?php
use Ramsey\Uuid\Uuid;
use Ramsey\Uuid\Exception\UnsatisfiedDependencyException;
$bucketName = "default";
// Establish username and password for bucket-access
$authenticator = new \Couchbase\PasswordAuthenticator();
$authenticator->username('Administrator')->password('Password');
// Connect to Couchbase Server - using address of a KV (data) node
$cluster = new CouchbaseCluster("couchbase://127.0.0.1");
// Authenticate, then open bucket
$cluster->authenticate($authenticator);
$bucket = $cluster->openBucket($bucketName);
class couchDb {
public function upsert($DocId, $doc)
{
$result = $bucket->upsert($DocId, $doc);
return ($result->cas);
}
}
解决方案
所以“$bucket”在类范围内是未知的。要在你的类中使用“bucket”,你可以注入这个实例。请查看“依赖注入”,如下所示:
class couchDb {
private $bucket;
public function __construct(THE_TYPE_WICH_RETURNS_OPENBUCKET $bucket)
{
$this->bucket = $bucket;
}
public function upsert($DocId, $doc)
{
$result = $this->bucket->upsert($DocId, $doc);
return ($result->cas);
}
}
推荐阅读
- android - android:onClick 属性定义在视图类 androidx.appcompat.widget.AppCompatButton
- c# - Rerun failed tests using Specflow.Retry
- node.js - 服务帐户:Google Analytics v4:错误用户没有任何 Google Analytics 帐户
- python - 如何使用 Holoviews 将多个绘图保存到一个 .HTML 页面?
- vue.js - Nuxt.js 仅客户端组件
- gradle - gradlew genSource 'Mods\NewMod\' 不是内部或外部命令、可运行程序或批处理文件
- python - 如何使用 pandas、python 和 ta-lib 从许多 csv 构建数据框以计算技术指标
- c++ - 是否可以使用 FetchContent 或等效方法通过 CMake 添加没有 CMakeLists.txt 的库?
- material-ui - 具有不同数量的单元格对齐的 MaterialUI 表格行
- javascript - 使用 .set() 从 JS 组件更改 Svelte 存储不适用于对象