Created
November 24, 2016 18:24
-
-
Save mathiasverraes/062d24cc98ace7f724f1f2d0f0d143eb to your computer and use it in GitHub Desktop.
faking method overloading
This file contains hidden or 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 | |
// method overloading example (not possible in php) | |
final class SomeEventListener { | |
public function when(EmployeeWasHired $event) { | |
// set a salary | |
} | |
public function when(EmployeeWasPromoted $event) { | |
// increase salary | |
} | |
} | |
// Faking method overloading. Noisy but good enough. | |
final class SomeEventListener { | |
public function when(Event $event) { | |
switch (true) { | |
case $event instanceof EmployeeWasHired: | |
return $this->whenEmployeeWasHired($event); | |
case $event instanceof EmployeeWasPromoted: | |
return $this->whenEmployeeWasPromoted($event); | |
} | |
} | |
public function whenEmployeeWasHired(EmployeeWasHired $event) { | |
// set a salary | |
} | |
public function whenEmployeeWasPromoted(EmployeeWasPromoted $event) { | |
// increase salary | |
} | |
} |
I also like a more generic approach
<?php
class Test {
public function on(Event $event) {
$eventName = (new ReflectionClass($event))->getShortName();
$methodName = 'on' . $eventName;
$callable = [$this, $methodName];
if ( !is_callable($callable) ) {
throw ListenerMethodNotImplemented::forEvent($event); // or early return
}
call_user_func($callable, $event);
}
protected function onEmployeeHired(EmployeeHired $event) {
// ...
}
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I really don't like switches used in this way - I think it makes method extraction a little harder to do. In this case, I'd prefer:
...but I agree with what you're saying in the thread! :)