Deferred chain
A few months ago, I wrote a small PHP class to help me create chainable interfaces (PHP people like to call these “fluent interfaces”) without having to retrofit old code. I call this DeferredChain.
Here is the source for DeferredChain.
The idea is that you extend DeferredChain and write a bunch of methods prefixed with ‘_’. These don’t have to return $this to enable you to chain them.
class MyChain extends DeferredChain {
protected function _doSomething() {
$f = file_get_contents('something.txt');
return $f;
}
// you can have method arguments of course
protected function _doSomethingElse($x) {
return $x*2;
}
}
$m = new MyChain;
$m->doSomething()->doSomethingElse(42);
//do whatever
// execute your chain step by step
while($res = $m->doNext()) {
$results[] = $res ;
echo $res;
}
// or all steps at once
$results = $m->doAll();
If you are still reading this post, here is a more interesting example.
$d = new DiggChain($user,$pass);
$d->login()->profile()
->index()->diggStories(4)->index()
->category()->buryStories(2)
->category('general')->diggMine($story_id)
->index();
$c = new CurlBase;
while(($requests = $d->doNext())) {
$c->addArr($requests);
$c->perform();
}
Here is the incomplete DiggChain.
This is how I like to write glue for loosely coupled cURL requests. For example, I wouldn’t use chains for just a series of HTTP requests that login at a website. I have been using the Curl Objects library, which provides a specialized class for tightly coupled HTTP requests. You should probably check that out if you use php-cURL.
Well that’s it for today. Stay tuned for more coding related posts.
6 Comments
July 22nd, 2009 at 4:44 am
There is an infinitive loop in DeferredChain->doNext. Am I right?
July 22nd, 2009 at 8:54 am
There is no infinite loop. There were some problems with doAll(), which I just fixed though.
July 23rd, 2009 at 12:01 am
My mistake, no loop of course.
I wanted to say that $this->pos is always -1.
$k = $this->pos+1;
doNext() always executes steps[0].
July 23rd, 2009 at 2:45 am
Seems I messed it up when I rewrote it. Thanks for pointing that out.
July 28th, 2009 at 7:57 am
This chaining is only concerned with function side affects i take it.
Am i missing something or won’t that digg chain blaze through the requests at super human speeds?
July 28th, 2009 at 12:08 pm
Yeah it would. You could either sleep() in the while() loop or use CurlObject’s sleeping options.
Leave a Reply
You must be logged in to post a comment.