Skip to content

Instantly share code, notes, and snippets.

@eliran-arkabi
Last active October 18, 2018 10:58
Show Gist options
  • Select an option

  • Save eliran-arkabi/64b12890632ae8128662b1907242981f to your computer and use it in GitHub Desktop.

Select an option

Save eliran-arkabi/64b12890632ae8128662b1907242981f to your computer and use it in GitHub Desktop.
<?php
/** Warning if use this trait on class has be use magic methods __call | __classStatic dont use it
** Just copy the code to your magic methods on the class
* To fire the call need to and end TryCatch
* example if you class Foo::test() to fire need to call Foo::testTry()
* example if you class $ob->test() to fire need to call $ob->testTry()
*/
trait TryCatchTrait{
public function __call($method, $arguments)
{
if (preg_match('/TryCatch$/', $method)){
//replace TryCatch
$method = str_replace('TryCatch', '', $method);
//try to call the method
try {
return call_user_func_array([$this, $method], $arguments);
} catch (\Exception $e) {
// catch all
$message = 'Exception catch on call Method: ' . $method . ' Class: ' . __CLASS__ . ' DIR: ' . __DIR__;
self::handelExceptions($e, $message);
}
}
}
public static function __callStatic($method, $arguments)
{
if (preg_match('/TryCatch$/', $method)){
//replace TryCatch
$method = str_replace('TryCatch', '', $method);
//try to call the method
try {
return call_user_func_array(__CLASS__ . "::$method", $arguments);
} catch (\Exception $e) {
// catch all
$message = 'Exception catch on call static Method: '. __CLASS__ . '::' . $method . ' DIR: ' . __DIR__;
self::handelExceptions($e, $message);
}
}
}
// over write this method on the class use this trait
private static function handelExceptions(\Exception $e, string $message)
{
echo $message;
echo "\nMessage:" . $e->getMessage() . "\n";
}
}
/* @@ Just for test remove this class on use @@ */
class Foo{
use TryCatchTrait;
public static function test($throw)
{
if ($throw){
throw new \Exception('Some Exception');
}
echo "test\n";
}
public function testOb($throw)
{
if ($throw){
throw new \Exception('Some Exception');
}
echo "test\n";
}
//custom handel
private static function handelExceptions(\Exception $e, string $message)
{
echo "handelExceptions class\n";
}
}
//object
$f = new Foo;
$f->testObTryCatch(false); // echo test
$f->testObTryCatch(true);// catch Exception
//static
Foo::testTryCatch(false); //echo test
Foo::testTryCatch(true); // catch Exception
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment