There is a PHP backend serving various requests and returning json.
Entry point (simplified):
try { switch ($method) { case 'login': $call = new Login($data); break; case 'list': $call = new List($data); break; default: $call = new WrongMethod($data); } $out = ['r' => $call(),'n' => (string)Error::OK,'e' => '']; } catch (Error $e) { $out = [ 'r' => $call::defaultResult())), 'n' => (string)$e->getCode(), 'e' => $e->getMessage() ]; } print_r(json_encode($out, JSON_UNESCAPED_UNICODE), false); Already saw the error? ;)
Problem: $call::defaultResult() - in the catch the $call object is not defined.
All classes bullet Error extends Exception and implement the interface
interface Call { public function __construct(array $data); public function __invoke(); public static function defaultResult(); } defaultResult needed because _invoke can return a scalar, a regular array, or an associative array, and if you use a value of one type for an error, the front will stumble upon deserialization. That is, I need to be guaranteed to get in the catch the same structure of the 'r' field as in the try block
I see two solutions:
Remove from the constructor everything that can throw an exception. I do not like this approach because in my constructors, I only check the input data for validity and bring it in if necessary. IMHO this functionality is the place in the constructor.
Go to the dark side and do something like this:
(I don’t like this option at all. It causes discomfort and loss of appetite.)
function getMethodClass($method) { switch ($method) { case 'login': return "Login"; case 'list': return "GetList"; default: return "WrongMethod"; } } $className = $callsNameSpace."\\" . getMethodClass($method); try { $call = new $className($data); ... } catch (Error $e) { $out = ['r' => call_user_func(array($className, 'defaultResult')), ... }
Attention, question!
Maybe I'm wrong about my phobias and the first (or second) option is quite good for yourself?
Maybe I earned and do not see a simple and obvious solution? So that it works fine and does not upset your soul?
UPD PHP 5.6