There are several ways to deal with errors, setting the error on some property of the service is my least favourite, because it is too easy to ignore. Plus you have keep track of it, meaning you’d have to blank it if you try to connect again. Which can also be forgotten, etc.
In general: never solve with state that which can also been solved without state
There are two options that are stateless; return a result object, or throw exceptions.
Return a result object
The result object could look like this:
class FtpConnectionResult
{
private $isSuccessfull ;
private $error;
public function __construct($isSuccessful, $error = '')
{
$this->isSuccessfull = $isSuccesul;
$this->error = $error;
}
public function isSuccessful()
{
return $this->isSuccessfull;
}
public function getError()
{
return $this->error;
}
}
And then the method would look like this:
$this->ftpConn = ftp_connect($this->host);
if (!$this->ftpConn) {
return new FtpConnectionResult(false, 'Unable to connect');
}
$login = ftp_login($ftpConn,$this->user,$this->password);
if (!$login) {
return new FtpConnectionResult(false, 'Unable to login to FTP. Invalid username and/or password.');
}
ftp_close($ftpConn);
return new FtpConnectionResult(true, null);
Note the pattern here:
Are we still ok?
– no → return
– yes → continue
Throw exceptions
This looks quite similar but throws exception rather than returning a result object. The main advantage here is that you can’t ignore exceptions, you have to deal with them, whereas you can ignore a result object.
You can use one of the built in exceptions, like RuntimeException
, or define your own, like so:
class FtpException extends RuntimeException
{
}
So then FtpException
is a specific kind of RuntimeException
, one that occurs when there is a problem connecting to an FTP server.
Then the method would look like this:
$this->ftpConn = ftp_connect($this->host);
if (!$this->ftpConn) {
throw new FtpException('Unable to connect');
}
$login = ftp_login($ftpConn,$this->user,$this->password);
if (!$login) {
return new FtpException(false, 'Unable to login to FTP. Invalid username and/or password.');
}
ftp_close($ftpConn);
Note the pattern here:
Are we still ok?
– no → throw exception
– yes → continue
Also note that if the connection was successful then it doesn’t return anything. It doesn’t have to. The sheer absence of an exception means the method succeeded.
Lastly, some general remarks on the class:
$ftpConn
should not be public in your class, it breaks encapsulation- Why is the method to connect called
ftpconn
? Do youftpconn
to an FTP server? Or do youconnect
to an FTP server?