Created
April 6, 2022 16:17
-
-
Save polerin/e46894921a5d5e31d04cc37c6cfde50c to your computer and use it in GitHub Desktop.
Dynamic method example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
interface IThingy | |
{ | |
function getClassifier() : string; | |
} | |
class DynamicMethodHost | |
{ | |
private string $methodPrefix = "__handle"; | |
public function operateOnAThing(IThing $Thingy) : void | |
{ | |
$methodName = $this->methodPrefix . $Thingy.getClassifier(); | |
// The other thing is that these could be injected strategies so they can | |
// be composed, would just require it be a slightly different check | |
if (method_exists($this, $methodName) { | |
$this->{$methodName}($Thingy); | |
return; | |
} | |
$this->defaultThingyHandler($Thingy); | |
} | |
private function defaultThingyHandler(IThing $Thingy) : void | |
{ | |
// whatever | |
} | |
private function __handleSpecificType(IThing $thingy) : void | |
{ | |
// specific whatver | |
} | |
} | |
class ThingyExample implements IThing | |
{ | |
private string $somethingWhatever = "specificType"; | |
public function __constructor(string $somethingWhatever) | |
{ | |
$this->setSomethingWhatever($somethingWhatever); | |
} | |
public function getClassifier() : string | |
{ | |
// honestly this could be anything from the string type of an enum to some | |
// field in a data object (such as post type) to just the hecking class name | |
return str_replace(" ", "", $this->somethingWhatever); | |
} | |
public function setSomethingWhatever(string $newSomethingWhatever) : void | |
{ | |
$this->somethingWhatever = $newSomethingWhatever; | |
} | |
} | |
// obviously you wouldn't just have these two things next to each other, | |
// these could be events passed into a handler or something like that. | |
$Host = new DynamicMethodHost(); | |
$Subject = new ThingieExample(); | |
$SubjectSpecified = new ThingieExample("this would fall through"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment