首页 > 解决方案 > 在类内的函数中访问 $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);
    }

}

标签: phpcouchbase

解决方案


所以“$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);
    }

}

推荐阅读