php - Enforce Method Call Required by Object -
i created ssh2 wrapper. have read constructor should not fail, ssh2 connection not done in wrapper, method connect()
. question is: how make sure connect()
called? need 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 best way ensure connect() called? should application call it?
$ssh = new uploader('host', 'user', 'pass'); $ssh->connect();
or in class methods?
... public function upload($source, $dest, $filename) { $this->connect(); ... } public function delete($file) { $this->connect(); ... }
neither of these seems ideal.
i thought making static method wrap constructor , connect, constructor have private , have read static methods undesirable (mostly unit testing).
i have read static methods undesirable (mostly unit testing).
static methods undesirable things, factory methods isn't 1 of them. make perfect sense there , not impact unit testing. so, go ahead , make static factory method.
Comments
Post a Comment