Search code examples
phpmongodbmongoidmongo-collection

return a mongo object php for mongocollection


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:[email protected]); 
                $this->dbLink = $this->conn->selectDB('profiles');
                return $this->dbLink;
    }

index.php

       $myMongo = new Mongo(); 
       $collection = new MongoCollection($myMongo,'user');

Solution

  • 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).