Ok, lets talk about some every-day-work. Directory iteration, file access, file information, etc. PHP has some functions to cope with those tasks quite well ... But! We want to write OOP code, so why don't we use objects to handle those tasks? The answer is ... again ... use the SPL! You can find a short overview of the SPL's file related classes at http://php.net/manual/en/spl.files.php. In addition to that, the DirectoryIterator class brings some exciting methods for iterating directories. I've assembled a small example that combines most of the possible workflow, but it covers only an itch of what those classes are capable of.
$sMyDirectory = '/tmp/somedir';
$oDirIterator = new DirectoryIterator($sMyDirectory);
foreach ($oDirIterator as $oIterItem) {
// $oIterItem is an instance of DirectoryIterator
if ($oIterItem->isFile()) {
//DirectoryIterator::getPathname() returns the full path
$oFile = new SplFileInfo($oIterItem->getPathname());
/*
* If it is a symlink, resolve it
* You can use getRealPath() for resolving
* symlinks in the path structure
*/
if ($oFile->isLink()) {
$oFile = new SplFileInfo($oFile->getLinkTarget());
}
if ($oFile->isWritable()) {
// We get an SplFileObject
$oOpenFile = $oFile->openFile("wb");
$oOpenFile->fwrite('Some Text, maybe even some UTF-8 Stuff? A €uro sign?');
// close the opened file the hard way, if you really need
// anyway, you can skip that, PHP does it for you.
unset($oOpenFile);
}
else {
throw new RuntimeException(
"Requested file is not writable!");
}
}
}