Skip to content

Instantly share code, notes, and snippets.

@will0
Created October 1, 2012 16:20
Show Gist options
  • Save will0/3812801 to your computer and use it in GitHub Desktop.
Save will0/3812801 to your computer and use it in GitHub Desktop.
Testables
function asserteq($lhs, $rhs) {
if($lhs != $rhs)
exit "$lhs != $rhs";
}
if(LOCAL)
$foo = new foo_direct(getenv('FOO_DB_STUFF'));
else
$foo = new foo_http(getenv('FOO_ENDPOINT'));
$foo->_set_auth('testy', 'secret');
$shame = 'I like to smell my own farts';
$foo->confess($shame);
asserteq(array($shame), $foo->review());
# direct impl
class foo_direct {
var $db;
var $auth_token;
var $user;
function __construct($dbstuff) {
$this->db = connectify($dbstuff);
}
function _set_auth($user, $secret) {
$this->auth_token = $this->user = null; // forget current creds first
$this->auth_token = authenticate($user, $secret); // throws on fail?
$this->user = $user;
return TRUE;
}
function confess($shame) {
$this->db->query("insert into shames (user, shame) values ('$user', '$shame')");
}
function review() {
$my_shame = $this->db->query("select shame from shames where user = '$user'");
return $my_shame;
}
}
// path without . means look at include path
require_once "services/foo_direct.php";
$user = $request['user'];
$secret = $request['password'];
$foo = new foo_direct(getenv('FOO_DB_STUFF'));
if(!@$foo->_set_auth($user, $secret))
fail_with_401();
switch($METHOD) {
case "POST":
$shame = $request['body'];
$foo->confess($shame);
do_200();
break;
case "GET":
$shames = $foo->review();
render($shames);
do_200();
default:
exit "screaming and shouting";
}
class foo_http {
var $endpoint;
var $user;
var $secret;
function __construct($endpoint) {
$this->endpoint = $endpoint;
}
function _set_auth($user, $secret) {
$this->user = $user;
$this->secret = $secret;
return TRUE;
}
function confess($shame) {
$status = curl_post($this->endpoint, array(
'user' => $this->user,
'secret' => $this->secret,
'shame' => $shame));
if($status != 200)
die "screaming";
}
function review() {
$status = curl_get($this->endpoint, array(
'user' => $this->user,
'secret' => $this->secret));
if($status != 200)
die "screaming";
}
}
@will0
Copy link
Author

will0 commented Oct 1, 2012

core things:

  • service endpoints not in code
  • credentials not in code (except in test example)
  • not shown: declare other service dependencies in your constructor (prevents cycles)

@will0
Copy link
Author

will0 commented Oct 1, 2012

oh yeah, and:

  • don't just new up stuff all over, add parameters if you need more services to do stuff until you don't have parameters anymore

@will0
Copy link
Author

will0 commented Oct 1, 2012

that leads you to the "man, this has a bunch of parameters", "man, this does a lot of stuff", "this does too much stuff", "lets break this into pieces" thoughts

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment