在类内部的函数中访问$ bucket的问题

问题描述 投票:0回答:1

我正在尝试构建一个可重用的db类,该类允许我针对我的ouchdb数据库访问基本的crud函数。当我尝试执行此功能时,出现以下错误。所以问题是如何从类内的函数访问$ bucket对象?

PHP注意:未定义的变量:存储在第26行PHP上的/var/www/html/PHRETS/couchBase.php致命错误:未捕获的错误:在null中调用成员函数upsert()/var/www/html/PHRETS/couchBase.php:26堆栈跟踪:

0 /var/www/html/PHRETS/retsphp.php(72):benchDb :: upsert('OpenHouse :: b769 ...',Object(OpenHouse))

1 {main}在第26行的/var/www/html/PHRETS/couchBase.php中抛出

这是我在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);
    }

}
php couchbase
1个回答
1
投票

因此“ $ 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);
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.