Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
| 1 | <?php |
||
| 9 | class EchoServer extends Server |
||
| 10 | { |
||
| 11 | const DEFAULT_PORT = 7; |
||
| 12 | |||
| 13 | public function __construct($address = null, $port = self::DEFAULT_PORT) |
||
| 14 | { |
||
| 15 | parent::__construct($address, $port); |
||
| 16 | $this->addHook(Server::HOOK_CONNECT, [$this, 'onConnect']); |
||
| 17 | $this->addHook(Server::HOOK_INPUT, [$this, 'onInput']); |
||
| 18 | $this->addHook(Server::HOOK_DISCONNECT, [$this, 'onDisconnect']); |
||
| 19 | $this->run(); |
||
| 20 | } |
||
| 21 | |||
| 22 | public function onConnect(Server $server, Socket $client, $message) |
||
| 23 | { |
||
| 24 | echo 'Connection Established', "\n"; |
||
| 25 | } |
||
| 26 | |||
| 27 | public function onInput(Server $server, Socket $client, $message) |
||
| 28 | { |
||
| 29 | echo 'Received "', $message, '"', "\n"; |
||
| 30 | $client->write($message, strlen($message)); |
||
| 31 | } |
||
| 32 | |||
| 33 | public function onDisconnect(Server $server, Socket $client, $message) |
||
| 34 | { |
||
| 35 | echo 'Disconnection', "\n"; |
||
| 36 | } |
||
| 37 | } |
||
| 38 | |||
| 40 |