kriswallsmith / spork

Experimental library for forking PHP
MIT License
587 stars 52 forks source link

MongoStrategy. Сlosing connection. Why? #41

Open cystbear opened 8 years ago

cystbear commented 8 years ago

Hi, I have found next in MongoStrategy

 If you use this strategy you MUST close your Mongo connection on the spork.pre_fork event.
     $mongo = new Mongo();
     $manager->addListener(Events::PRE_FORK, array($mongo, 'close'));

I can not understand why I need to do this?

Also my code looks like, I mean that I open connection out of logic closure that runs inside fork.

$mongo  = new \MongoClient();
$db     = $mongo->selectDB(DB_NAME);
$coll   = $db->selectCollection(COLL_NAME);
$cursor = $coll->find([/*some query here*/]);

$dispatcher = new SporkDispatcher\EventDispatcher();
$dispatcher->addListener(SporkDispatcher\Events::PRE_FORK, function() use($mongo) {
    $mongo->close();
});
$manager  = new Spork\ProcessManager($dispatcher);
$strategy = new Spork\Batch\Strategy\MongoStrategy(5);

$manager->process($cursor, function($document) {
    $document; // some work here
}, $strategy);

There are few more questions:

So, looks like @kriswallsmith will be helpful here.