强制执行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 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).
我创建了一个ssh2包装器。 我已经读过构造函数不应该失败,所以ssh2连接不是在包装器中完成的,而是通过方法 确保调用connect()的最佳方法是什么? 应用程序应该调用吗? p>
或者在类方法中? p>
这些似乎都不理想。 p>
我还想过制作一个静态方法来包装 构造函数和连接,但是构造函数必须是私有的,我还读过静态方法是不可取的(主要是单元测试)。 p>
div> connect() code>完成的。 我的问题是:如何确保调用
connect() code>? 我也只需要调用一次。 p>
class uploader {
private $ user; 私人$ pass; private $ host;
private $ ssh = null; private $ sftp = null;
public function __construct($ host,$ user,$ pass){
$ this-> host = $ host; $ this-> user = $ user; $ this-> pass = $ pass;
}
公共函数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) ;
}
}
}
code> pre>
$ ssh = new uploader('host','user','pass');
$ ssh-> connect();
code> pre>
...
公共函数上传($ source,$ dest) ,$ filename){
$ this-> connect();
...
}
公共函数删除($ file){
$ this-> connect();
.. 。
}
code> pre>
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.