Skip to content

Instantly share code, notes, and snippets.

@shiwork
Last active November 11, 2016 17:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shiwork/f9cdf5fd09bd369383279a5be2842433 to your computer and use it in GitHub Desktop.
Save shiwork/f9cdf5fd09bd369383279a5be2842433 to your computer and use it in GitHub Desktop.
silent kill
<?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();
@shiwork
Copy link
Author

shiwork commented Nov 11, 2016

$ php silent_kill.php
create instance
echo process
create instance

@shiwork
Copy link
Author

shiwork commented Nov 11, 2016

constructorは失敗しないようにしてやらないとだめ
処理が即時で完結するような箇所じゃないとだめ

@shiwork
Copy link
Author

shiwork commented Nov 11, 2016

constructorの内部で例外を処理してchainingのflagを処理してやれば良さそう

@shiwork
Copy link
Author

shiwork commented Nov 11, 2016

% php silent_kill.php
success create instance
echo process
success create instance
fail create instance

@shiwork
Copy link
Author

shiwork commented Nov 11, 2016

  • トランザクション
  • handle対象外のpublicなメソッド

辺りのケアはケースに依るけど意識する必要がある

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment