nelwhix / filepath
该软件包最新版本(v1.0.1)没有可用的许可证信息。
不同操作系统架构的文件输入/输出实用工具
v1.0.1
2023-05-27 07:08 UTC
Requires (Dev)
- pestphp/pest: ^2.6
This package is auto-updated.
Last update: 2024-09-27 10:04:55 UTC
README
一个简单的类,包含一些静态方法,用于在系统架构无关的情况下正确操作文件路径
动机
我在一个遗留的PHP项目中工作,其中有很多这样的代码
$routes = include(__DIR_ . DIRECTORY_SEPARATOR . 'src' . DIRECTORY_SEPARATOR . 'routes.php');
然后我想起了golang的filepath包可以流畅地连接一个URL。因此,这是golang的path/filepath包方法的移植
安装
composer require nelwhix/filepath
用法
- 连接方法:使用静态'join'方法,之前示例的代码将看起来像这样
$url = \Nelwhix\Filepath\Filepath::join(__DIR__, 'src', 'routes.php'); $routes = include($url);
- 基本方法:基本方法返回传递给它的任何文件路径的最后部分。例如
\Nelwhix\Filepath\Filepath::base("/foo/bar/baz.js"); // this will return "baz.js"
- 绝对路径方法:abs方法返回给定文件路径的绝对路径
\Nelwhix\Filepath\Filepath::abs("Filepath.php"); // this returns "\C:\Users\USER PC\Documents\Open Source contributions\filepath\src\Filepath.php"
- 目录方法:dir方法返回路径中的目录
\Nelwhix\Filepath\Filepath::dir("/foo/bar/baz.js") // returns "/foo/bar"
- 清理方法:clean方法从文件路径中删除重复和尾随的反斜杠,例如
\Nelwhix\Filepath\Filepath::clean("//dirty///path////"); // this returns /dirty/path
- 扩展方法:ext方法返回文件路径中文件的扩展名。如果传递的是目录,则返回空字符串。
\Nelwhix\Filepath\Filepath::ext("/src/routes.php"); // returns ".php"
- 分割方法:split方法返回一个包含目录和文件的文件路径的对象
$split = \Nelwhix\Filepath\Filepath::split("./Documents/side-projects/filepath/composer.json"); $split->dir; // ./Documents/side-projects/filepath $split->file; // composer.json
- 遍历方法:walk方法接受一个目录和一个回调函数,该回调函数将在目录中的每个文件上运行。
Filepath::walk("C:\Users\USER PC\Documents\\300L books", function (\DirectoryIterator $param) { if($param->isDot()) return; echo $param->getFilename() . "\n"; });
- glob方法:glob方法返回目录中匹配模式的文件。要返回所有以".php"结尾的文件
Nelwhix\Filepath\Filepath::glob(".php", "side-projects/src"); // returns an array containing the files matching the pattern