如何以OOP方式处理文件


How to handle files in an OOP way?

我需要复制、移动和删除文件。

是否有任何组件或类用于此?

我发现了这个,但它只会移动:http://api.symfony.com/master/Symfony/Component/HttpFoundation/File/File.html

或者我应该坚持使用本机函数?

关于Symfony框架,您可以查看Symfony''Component''Filesystem''Filesystem

您发布的链接是HttpFoundation中的一个类,仅用于上传的文件。

PHP有许多处理文件系统的功能。

  • copy()函数顾名思义——复制文件
  • rename()函数实际上重命名和/或移动文件。作为mv命令,linux用户将熟悉这种行为
  • unlink()函数用于删除文件

PHP的文档中有一整节专门用于文件系统操作的功能。


当您在代码中实现这些函数以及如何实现这些函数时,面向对象的方法将发挥作用。

您可以启动自己的帮助程序类来包装过程命令吗?或者,您可以浏览一些流行的文件系统助手类或类似类的框架。

class File {
    public static function exists($file) {
        return file_exists($file);
    }
    public static function copy($file, $destination) {
        // checks
        return copy($file, $destination);
        // error handling
    }
    public static function move($file, $destination) {
        return rename($file, $destination);
    }
    public static function delete($file) {
        return unlink($file);
    }
}
File::copy( 'test.txt', 'copy.txt' );