Вопрос

I have a mongo class, which I later want to add CRUD functions into it, but as of now I want to write my own collection functions after I created objoect of Mongo, so anytime I want to use mongodb I just create object of my class, and write the commands

but it gives me this error:

Exception raised : Error (2) : "MongoCollection::__construct() expects parameter 1 to be MongoDB, object given

How can I get it as MongoDB,

mongo.class.php

   class Mongo
   {
        public function __construct(){
               $this->connect();
        }
        public function connect{
                $this->conn = new \Mongo("mongodb://admin:123456@192.168.2.3); 
                $this->dbLink = $this->conn->selectDB('profiles');
                return $this->dbLink;
    }

index.php

       $myMongo = new Mongo(); 
       $collection = new MongoCollection($myMongo,'user');
Это было полезно?

Решение

I suppose the problematic line should be written like this:

$collection = new MongoCollection($myMongo->dbLink, 'user');

You seem to expect that Mongo class constructor will return the value returned by connect method. But that's just not true: constructor returns the whole object (which properties may - and may be not - defined as it executes).

Some might say that dbLink property should not be exposed directly, and getter method should be used instead:

private $dbLink;
...
public function getDb() {
  return $this->dbLink;
}
...
$collection = new MongoCollection($myMongo->getDb(), 'user');

Me, I don't think this is necessary in this case, as your class seems to be tight-coupled with Mongo itself (which is, by me, what should be fixed first).

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top