Last active
November 11, 2016 17:40
-
-
Save shiwork/f9cdf5fd09bd369383279a5be2842433 to your computer and use it in GitHub Desktop.
silent kill
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 | |
/** | |
* Class SilentKill | |
* | |
* @method $this echo() | |
* @method $this process() | |
*/ | |
class SilentKill{ | |
private $chaining_continue = true; | |
public function __construct($exception_class = null) | |
{ | |
if ($exception_class) { | |
try { | |
throw new $exception_class; | |
} catch (Exception $e) { | |
$this->chaining_continue = false; | |
echo 'fail create instance' . PHP_EOL; | |
} | |
} else { | |
echo 'success create instance' . PHP_EOL; | |
} | |
} | |
/** @noinspection PhpInconsistentReturnPointsInspection */ | |
public function __call($method, array $args) | |
{ | |
$chaining_method = 'chaining' . ucfirst($method); | |
if (method_exists($this, $chaining_method)) { | |
if (!$this->chaining_continue) { | |
// 既に例外が生じていたら処理を行わずにmethod chainを続行する | |
return $this; | |
} | |
try { | |
return $this->$chaining_method($args); | |
} catch (Exception $e) { | |
// method chainをdummyに切り替える | |
$this->chaining_continue = false; | |
// 例外の時は何もせずにmethod chainを続行する | |
return $this; | |
} | |
} | |
} | |
/** @noinspection PhpUnusedPrivateMethodInspection */ | |
private function chainingEcho() | |
{ | |
echo 'echo process' . PHP_EOL; | |
return $this; | |
} | |
/** | |
* @return $this | |
*/ | |
/** @noinspection PhpUnusedPrivateMethodInspection */ | |
private function chainingProcess() | |
{ | |
// 例外で失敗する処理 | |
throw new Exception; | |
return $this; | |
} | |
} | |
(new SilentKill())->echo()->process(); | |
// 内部で例外が生じたら移行のmethod chainは何もしない | |
(new SilentKill())->process()->echo(); | |
// constructorで例外が生じるケース | |
(new SilentKill(Exception::class))->echo()->process(); |
constructorの内部で例外を処理してchainingのflagを処理してやれば良さそう
% php silent_kill.php
success create instance
echo process
success create instance
fail create instance
- トランザクション
- handle対象外のpublicなメソッド
辺りのケアはケースに依るけど意識する必要がある
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
constructorは失敗しないようにしてやらないとだめ
処理が即時で完結するような箇所じゃないとだめ