0

我正在使用 Kohana MVC 框架。我想添加一个可与 PHPCassa 对象(Cassandra NoSQL)一起使用的模块。

问题是,当我创建对象时,我拥有它的所有属性,并且可以在构造中与它进行交互,但是当我从不同的地方创建它时,它会作为空对象返回。

我确信我错过了一些东西,因为我对 OOP 很陌生。请帮帮我。

模块文件

<?php

// Loading cassandra libraries, tried to load them here, did not help
//require 'application/modules/cassandra/lib/connection.php';
//require 'application/modules/cassandra/lib/columnfamily.php';

class Cassandra {

    function __construct($columnFamily) {
        // Loading cassandra libraries
        require 'application/modules/cassandra/lib/connection.php';
        require 'application/modules/cassandra/lib/columnfamily.php';

        $pool = new ConnectionPool('localhost');
        $cf = new ColumnFamily($pool, $columnFamily);

        // print_r($cf); // This will print object with all the proporties that I can use

        return $cf;
    }

将加载模块并创建空对象的类

<?php

class Controller_Main extends Controller {

    public function action_index() {
        $a = new Cassandra('timeline');
        echo '<pre>';
        print_r($a); // This will print out empty Cassandra object
        die();

        //$this->response->body('hello, world!');
    }

}
4

2 回答 2

1

ConnectionPoolColumnFamily仅在构造函数中使用,因此一旦完成,它们将不再存在。此外,当使用new调用 PHP 构造函数时,它会返回一个新实例,而不是return您尝试的值。也许尝试这样的事情:

<?php

require_once 'application/modules/cassandra/lib/connection.php';
require_once 'application/modules/cassandra/lib/columnfamily.php';

class Cassandra {

    public $pool = null;
    public $cf = null;

    function __construct($columnFamily) {

        $this->pool = new ConnectionPool('localhost');
        $this->cf = new ColumnFamily($this->pool, $columnFamily);

        return $this;

    }
}

尝试这样做,然后var_dump()$a上查看整个 Cassandra 对象或在$a->cf上查看 ColumnFamily 对象。应该告诉你你需要什么。

于 2012-04-09T12:40:54.583 回答
0

做错了,你在构造函数中创建了两个对象,一个是 Cassandra对象,另一个是 ColumnFamily显然new Cassandra('timeline');将返回Cassandra对象。

试试这种方式:

class Cassandra {

    static function LoadCassandra($columnFamily) {
        // Loading cassandra libraries
        require 'application/modules/cassandra/lib/connection.php';
        require 'application/modules/cassandra/lib/columnfamily.php';

        $pool = new ConnectionPool('localhost');
        $cf = new ColumnFamily($pool, $columnFamily);

        return $cf;
    }

并使用它:

class Controller_Main extends Controller {

    public function action_index() {
        $a =  Cassandra::LoadCassandra('timeline');
        echo '<pre>';
        print_r($a); // This will print out empty Cassandra object
        die();

        //$this->response->body('hello, world!');
    }

}
于 2012-04-09T12:46:49.310 回答