MongoDB PHP OOP非对象的错误属性


MongoDB PHP OOP - Error Property of non-object

我试图使用OOP PHP访问我的mongodb集合。然而在页面上它没有返回任何东西,但是当我查看apache错误日志时,它显示

PHP注意:试图在main.php第22行获取非对象的属性

下面是我使用的代码:db.php

class db {
    static $db = NULL;
    static function getMongoCon()
    {
        if (self::$db === null)
        {
            try {
                $m = new Mongo('mongodb://{user}:{password}@{host}:{port}/{database}');
            } catch (MongoConnectionException $e) {
                die('Failed to connect to MongoDB '.$e->getMessage());
            }
            self::$db = $m;
        }
            else
        {
            return self::$db;
        }
    }
   }

main.php

//load db files
require_once('db.php');
class test{
   public function __construct() {
       echo $this->output();
   } 
   public function output() {
       $con=db::getMongoCon();
       $db=$con->database;
       $test=$db->collection;
       $n=$test->find();
       print_r($n);
   } 
}
new test();

这一切都使用过程代码,我已经能够在这个方法中插入数据-所以它应该工作(我已经删除了数据库的详细信息在这里明显的安全原因)。

注意:我已经读了这个,但它仍然不工作。

这是一个非常简单的错误。您正在使用工厂模式,但是第一次调用getMongoCon方法时,它将返回null:

class Db
{//convention: Upper-Case classes
    private static $_db = null;//using this pattern a public static is a bad idea
    public static function getMongoCon()
    {//^^ best specify public/private/protected
        if (self::$db === null)
        {//first time called: this is true
            try {
                //I'd assign immediatly here, but hey...
                self::$db = new Mongo('mongodb://{user}:{password}@{host}:{port}/{database}');
                $m = new Mongo('mongodb://{user}:{password}@{host}:{port}/{database}');
            }
            catch (MongoConnectionException $e)
            {
                die('Failed to connect to MongoDB '.$e->getMessage());
            }
            self::$db = $m;
        }
        //!!leave out else to fix!!
        return self::$db;
    }
}

正如您所看到的,我所做的只是省略了else,无论self::$db 的值是什么都必须返回它。但是如果 null,则永远不会进入包含返回语句的else分支。
throw-catch块也没有真正的原因。显然,您的代码依赖于db连接才能工作,如果它不能正常工作,则没有备份,因此只需让它抛出(并停止)。

为了完整起见,下面是我编写上述代码的方法:
class Db
{
    private static $_db = null;
    public static function getMongoCon($new = false)
    {//allow for another connection, you never know...
        if (self::$_db === null)
        {
            self::$_db = new Mongo('mongodb://{user}:{password}@{host}:{port}/{database}');
        }
        if (true === !!$new)
        {
            return new Mongo('mongodb://{user}:{password}@{host}:{port}/{database}');
        }
        return self::$_db;
        //or, short 'n messy:
        return (!$new ? self::$_db : new Mongo('mongodb://{user}:{password}@{host}:{port}/{database}'));
    }
}