强制执行对象所需的方法调用
我创建了一个 ssh2 包装器。我读过构造函数不应失败,因此 ssh2 连接不是在包装器中完成的,而是通过方法 connect()
完成的。我的问题是:如何确保调用 connect()
?我也真的只需要调用一次。
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);
}
}
}
确保调用 connect() 的最佳方法是什么?应用程序应该调用它吗?
$ssh = new uploader('host', 'user', 'pass');
$ssh->connect();
或者在类方法中?
...
public function upload($source, $dest, $filename) {
$this->connect();
...
}
public function delete($file) {
$this->connect();
...
}
这些似乎都不理想。
我还考虑过创建一个静态方法来包装构造函数并连接,但是构造函数必须是私有的,而且我还读到静态方法是不可取的(主要只是用于单元测试)。
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).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
静态方法对于某些事情来说是不可取的,但工厂方法不是其中之一。它们在那里非常有意义,并且不会影响单元测试。因此,继续创建一个静态工厂方法。
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.
最简单的方法是在构造函数中调用 connect() ,并确保创建析构函数来断开连接。
The easiest way is to call connect() in your constructor and be sure to make a destructor function to disconnect your connection.