【问题标题】:Problem accessing $bucket in a function inside a class在类内的函数中访问 $bucket 时出现问题
【发布时间】:2020-02-06 00:10:58
【问题描述】:

我正在尝试构建一个可重用的 db 类,它允许我针对我的 couchbase db 访问基本的 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);
    }

}

【问题讨论】:

  • 对于初学者来说,将您的存储桶声明移到函数上方的类中
  • 请注意,CouchDB 和 Couchbase 不是一回事,我建议重命名你的类以避免混淆

标签: php couchbase


【解决方案1】:

所以“$bucket”在类范围内是未知的。要在你的类中使用“bucket”,你可以注入这个实例。请像这样查看“Dependency injection”:

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);
    }

}

【讨论】:

  • 如何找到替换“THE_TYPE_WICH_RETURNS_OPENBUCKET”的类型
  • 我不认为该类型提示不是严格要求的,但我认为他的意思是它是由 openBucket 返回的类型。那可能是“IBucket”或“Bucket”。
猜你喜欢
  • 1970-01-01
  • 2021-07-16
  • 2022-12-30
  • 1970-01-01
  • 2019-12-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多