开发者

Enforce Method Call Required by Object

I created an ssh2 wrapper. I have read that a constructor should not fail, so the ssh2 connection is not done in the wrapper, but by a开发者_StackOverflow method connect(). My question is: how do I make sure that connect() is called? I also really only need it to be called once.

class uploader {
   private $user; private $pass; private $host;
   private $ssh = null; private $sftp = null;
   public function __construct($host, $user, $pass) {
      $this->host = $host; $this->user = $user; $this->pass = $pass;
   }
   public function connect() {
      if ($this->ssh === null) {
         $this->ssh = ssh2_connect($this->host);
         ssh2_auth_password($this->ssh, $this->user, $this->pass);
         $this->sftp = ssh2_sftp($this->ssh);
      }
   }
}

What is the best way to ensure that connect() is called? Should the application call it?

$ssh = new uploader('host', 'user', 'pass');
$ssh->connect();

Or in the class methods?

...
public function upload($source, $dest, $filename) {
   $this->connect();
   ...
}

public function delete($file) {
   $this->connect();
   ...
}

Neither of these seems ideal.

I also thought about making a static method that would wrap the constructor and connect, but then the constructor would have to be private and I have also read that static methods are undesirable (mostly just for unit testing).


I have also read that static methods are undesirable (mostly just for unit testing).

Static methods are undesirable for some things, but factory methods isn't one of them. They make perfect sense there and do not impact unit testing. So, go ahead and make a static factory method.


The easiest way is to call connect() in your constructor and be sure to make a destructor function to disconnect your connection.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜