I am having trouble coming up with a solution to handle success or failure(errors) that is consistent throughout my whole application, so far I have been stuck deciding from 3 possible solutions.(I am relatively new to OOP)
For example, if I wanted to login a remote api using CURL, I could make a class with methods structured similar to the following.
class Api
{
var $curl;
var $user;
var $pass;
var $buffer;
function __construct($user,$pass)
{
$this->curl = new curl();
$this->user = $user;
$this->pass = $pass;
}
functon login()
{
$url = 'http://example.com/login/';
$postfields = array($user => $this->user, $pass => $this-pass);
$this->buffer = $this->curl->post($url,$postfields);
}
}
After using login() we have some possible outcomes, successful login, bad login(with info from api such as user/pass incorrect), failed pageload(server unavailable) or possibly CURL errors.(many more issues possible but listed enough)
One basic approach would be create another method loginSuccessful()
loginSuccessful()
{
if(strstr($this->buffer,'Welcome user: "zzzz"'))
return true;
if(strstr($this->buffer,'Incorrect user or pass'))
return false;
if(strstr($this->buffer,'server unavailable'))
return false;
if(curl_error($this->curl->ch))
return false;
else
return false;
}
I could call this within the login() method after we post the data.
functon login()
{
$url = 'http://example.com/login/';
$postfields = array($user => $this->user, $pass => $this-pass);
$this->curl->post($url,$postfields);
if(loginSuccessul())
return true;
else
false;
}
This way is of course too basic and doesn't give much information about the error, to improve this I could return true still if successful or a error message if unsuccessful(instead of false).
loginSuccessful()
{
if(strstr($this->buffer,'Welcome user: "zzzz"'))
return true;
if(strstr($this->buffer,'Incorrect user or pass'))
return 'Incorrect user or pass';
if(strstr($this->buffer,'server unavailable'))
return 'server down';
if(curl_error($this->curl->ch))
return curl_error($this->curl->ch);
else
return 'some other error';
}
We use this the same as before, however something doesn't feel right about returning different types.(sometimes boolean, sometimes strings)
Another possible way would be to keep the true/false style as in the first method, but build another method like loginError(), which we place with login() again like
functon login()
{
...
....
if(loginSuccessul())
return true;
else
return loginError();
}
This now gives us some detailed error messages, but even this method doesn't feel right because overall I am mixing alot of text information with logic, also seems like I am breaking some SOLID principles.
Possibly the problem is with the class structure and my approach, all what I am doing is incorrect because I am working within a bad structure/mindset.
Thanks in advance for any thoughts.