SitePoint Sponsor |
|
User Tag List
Results 1 to 17 of 17
Threaded View
-
Nov 30, 2005, 21:27 #1
- Join Date
- Apr 2003
- Location
- London
- Posts
- 2,423
- Mentioned
- 2 Post(s)
- Tagged
- 0 Thread(s)
Mad idea - overload as mini domain language
Hi.
This comes out of an idea to use the overload capability in PHP5 for writing terser, declarative statements. In particular I have been rethinking the mock objects interface to Simpletest. For quite a while I have wanted to define a mock like so...
PHP Code:interface Doubler {
function double();
}
class TestOfStuff extends UnitTestCase {
function testStuffUsingDoubler() {
$this->MockDoubler->double->expect(13)->give(26);
$stuff_with_doubler = new Stuff(new MockDoubler());
...
}
}
.
The main point is that a lot of magic can happen in that mock declaration. This really will be all of the syntax. Compare with the situation now where a generate call has to be made, then the mock created and then an expectation set on it and finally thereturn value is set. I've gone from five lines to two. This way works with dependency injection too.
It can be extended to multiple instances and multiple method calls like so...
PHP Code:$this->MockDoubler(1)->double->at(1)->expect(13)->give(26);
How about an ActiveRecord subclass like this...
PHP Code:class Person extends ActiveRecord {
function __construct($transfer = false) {
$this->varchar(255)->given_name->not_null;
$this->varchar(255)->family_name->not_null;
$this->varchar(2)->iso_country('uk');
$this->ContactEmail->emails;
$this->key('given_name', 'family_name')->unique;
parent::__construct($transfer);
}
}
class ContactEmail extends ActiveRecord { ... }
To set up a new one...
PHP Code:$transaction = new MysqlTransaction();
$marcus = new Person();
$marcus->first_name = 'Marcus';
$marcus->family_name = 'Baker';
$marcus->emails->add->address = 'marcus@lastcraft.com';
$marcus->save($transaction);
$transaction->commit();
Implementation aside, I think it has a lot in common with the ruby style small domain languages.
I bet there are other uses too.
yours, MarcusMarcus Baker
Testing: SimpleTest, Cgreen, Fakemail
Other: Phemto dependency injector
Books: PHP in Action, 97 things
Bookmarks