Refactoring the old FTP API usage

at 2009-06-30 in Examples by friebe (0 comments)

If you are running an XP release before 5.7.3 and are still using the old FTP API (e.g. FtpConnection::put(), FtpConnection::get(), etcetera), this will no longer work. These methods have been deprecated since October 2007 when RFC #0140 was implemented but have continued to work until recently. But as the FTP API has been rewritten and in this course these deprecated methods have been removed, now it's finally time to migrate!



Here's an example of the old API's usage (from a real-life application, shortened of error handling for brevity):
<?php 
$c= new FtpConnection($url);
$c->connect();
$c->setPassive();
$c->put($imageFile->getUri(), $storage.$imageName, FTP_BINARY);
$c->put($thumbFile->getUri(), $storage.$thumbName, FTP_BINARY);
$c->close();
?>

Notes:
  • A setPassive() call can be eliminated by prepending ?passive=1 to the URL
  • The connect()method returns the connection instance
  • As noted above, the put method has been deprecated and replaced by various methods in FtpDir and FtpFile classes.

Knowing this, migrating to the new API can be accomplished as follows:
<?php 
with
($c= create(new FtpConnection($url))->connect()); {
$stor= $c->rootDir()->getDir($storage);
$stor->newFile($imageName)->uploadFrom(new FileInputStream($imageFile), FTP_BINARY);
$stor->newFile($thumbName)->uploadFrom(new FileInputStream($thumbFile), FTP_BINARY);
$c->close();
}
?>

The other advantages this new approach has are:
  • If the "storage" directory on the remote system does not exist, an exception will be thrown on line 2. This would have been indistinguishable in the old way
  • By using the FtpDir::newFile() method, we also ensure the file does not exist yet (if it doesn't matter, we would simply exchange newFile by file, if we'd like to ensure it exists we'd use getFile instead). In any case, it will raise an error if "imageName" refers to a directory!



Tip: More examples on rewriting API calls can be found in the examples in RFC #0140!



Subscribe

You can subscribe to the XP framework's news by using RSS syndication.


Categories

News
General
PHP5
Announcements
RFCs
Further reading
Examples
Editorial
EASC
Experiments
Unittests
Databases
5.8-SERIES

Related

Find related articles by a search for «Refactoring».