Skip to content

Instantly share code, notes, and snippets.

@mcamiano
Last active January 19, 2024 20:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mcamiano/00592fb400e5043d8acd to your computer and use it in GitHub Desktop.
Save mcamiano/00592fb400e5043d8acd to your computer and use it in GitHub Desktop.
Presenter handshakes to make Pfriendly Pfriends
<?php
class Pfriend {
private $bff="BFF";
private $allowed=array('A','B','C'=>'C');
private $notallowed=array('D','E','F'=>'G');
public function makePfriend(PfriendPresenter $pfriendpresenter) {
$that=$this; // make a local variable that is usable in a closure
$presentables = array('allowed','bff'); // we can change this with "Logic"
// Returns a closure with the object reference in it
return $pfriendpresenter->acceptAccess(function($property,$default='') use ($that, $presentables) {
if (property_exists($that,$property) && in_array($property,$presentables)) {
// returns a scalar or a stdClass object of only public properties
// Caller is expected to know intimately what to do with these things
return is_scalar($that->$property) ? $that->$property : json_decode(json_encode($that->$property), true);
}
return $default;
});
}
}
class PfriendPresenter {
private $accessor;
private function __construct() { }
public function acceptAccess(Closure $accessor) {
$this->accessor = $accessor;
return $this;
}
// Need to do Presenter::forPfriend($somepfriend) to get a presenter
public static function forPfriend(Pfriend $pfriend) {
$pf = new PfriendPresenter();
return $pfriend->makePfriend($pf);
}
public function bff() {
$bff = call_user_func( $this->accessor, 'bff');
return "La te da! ".$bff;
}
public function notallowed($default) {
return call_user_func( $this->accessor, 'notallowed', $default);
}
public function allowed() {
return call_user_func( $this->accessor, 'allowed');
}
}
$somePfriend = new Pfriend();
$pfriendView = PfriendPresenter::forPfriend( $somePfriend );
echo $pfriendView->bff() . "\n";
echo "Not allowed: <".$pfriendView->notallowed('some default').">\n";
echo "Allowed: <".print_r((array)$pfriendView->allowed(),true).">\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment