I'm working on a large PHP project, alone, and for years I did a lot of procedural programming, but now I'm trying to switch over to OOP, since I feel like it's finally matured enough in PHP and my knowledge of it isn't as poor. In my class methods I was considering returning in a consistent way that can be used in both PHP code and also be sent out over JSON API. I've tried to search for this, but either I'm doing it completely wrong and no one else thought of an idea this terrible or I just am not searching the proper way.
So in general I'm curious if there is a way to have consistent returns that are easily workable in both code and to send back out over APIs.
What I have in mind is:
public function doThing($stuff) {
$result = new stdClass();
$result->success = False;
if ($stuff == 'not correct') {
$result->error = 'Not correct, guy.';
return $result;
}
$result->success = True;
return $result;
}
So then it's a matter of
$check = $Class->doThing($otherstuff);
if ($check->success == True) {
do whatever is true
} else {
do whatever is false, show/return $check->error
}
And with JSON it's as simple as:
echo json_encode($check);
So on the client library you just have to do the same success check and error display. And of course I can add in other things to return as well, such as results from a database query or what have you.
Is this correct? Would it be normal/not a bad thing to do this for many of the common methods? Potential benefits I considered would be to insert ACL right into the method if I needed to or anything else, so I wouldn't have to do all of the error checking prior to the method being called.
I feel like perhaps I'm being too verbose and there's a better way.