-
Notifications
You must be signed in to change notification settings - Fork 1
PHP FileHelper
- Purpose
- Code Docs
- Relative Path
- Validating Items
- Loading Files
- Getting Folder Contents
- Creating Folders
- Writing to Files
The FileHelper class provides an easy way of accessing files and folders using a relative path.
Automatically generated documentation for FileHelper is available here:
http://n2framework.com/phpDoc/v2.0.1/classes/N2f.FileHelper.html
The main component of the FileHelper class is making it easier to work with files when using a relative path. Instead of having to copy the relative path around in a constant or variable, you can now simply use the ~ character in your file paths.
require('../inc/myfile.php'); // relative path depends on request entry file, must be maintained
$Fh = new \N2f\FileHelper('../');
$Fh->Load("~/inc/myfile.php"); // relative path is based on what FileHelper is created with, managed for youIf a FileHelper class is instantiated without providing an explicit value for the relative directory, the class will attempt to fallback onto './' as the default value.
If no ~ is provided in the path for any argument to a method, the relative path will not be substituted.
Finally, if at any point you should need to know what the relative path is set as for a given FileHelper, simply call the GetRelDir() method.
The class provides ways of validating that both files and folders exist:
if ($Fh->FileExists("~/inc/myfile.php")) {
// executes if the ../inc/myfile.php file exists
}
if (!$Fh->FolderExists("~/inc/")) {
// executes if the ../inc/ folder doesn't exist
}There are two methods available for loading files. One will simply load the file as if you were doing a require() call, while the other will retrieve a file's contents.
// Load the file, similar to require but with relative path translation
$Fh->Load("~/inc/myfile.php");
// Get the file contents, similar to file_get_contents but with relative path translation
$Fh->GetContents("~/inc/myfile.php");Three methods on FileHelper are devoted to retrieving the list of items inside a directory.
// Use GetFolderFiles to retrieve a list of all files in a directory (cannot be recursive)
$Files = $Fh->GetFolderFiles("~/inc/");
// Use GetFolderFolders to retrieve a list of all folders in a directory (can be recursive)
$Folders = $Fh->GetFolderFolders("~/");
// Use GetFolderItems to retrieve a list of all items in a directory (can be recursive)
$Items = $Fh->GetFolderItems("~/", true);Creating folders can also be done using a relative path:
$Fh->MakeFolder("~/temp/");And finally, writing to (and creating) files can be done using a relative path:
$Fh->PutContents("~/temp/site_is_offline.txt", "true");