Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
faking method overloading
<?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
}
}
@assertchris

This comment has been minimized.

Copy link

commented Nov 24, 2016

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:

public function when(Event $event) {
    // switch (true) {
    //     case $event instanceof EmployeeWasHired:
    //         return $this->whenEmployeeWasHired($event);
    //     case $event instanceof EmployeeWasPromoted:
    //         return $this->whenEmployeeWasPromoted($event);
    // }

    if ($event instanceof EmployeeWasHired) {
        return $this->whenEmployeeWasHired($event);
    }

    if ($event instanceof EmployeeWasPromoted) {
        return $this->whenEmployeeWasPromoted($event);
    }

    throw new InvalidArgumentException("not implemented");
}

...but I agree with what you're saying in the thread! :)

@pr0nbaer

This comment has been minimized.

Copy link

commented Nov 24, 2016

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
You can’t perform that action at this time.