tobento / service-file-creator
轻松创建文件。
1.0.1
2023-11-10 16:18 UTC
Requires
- php: >=8.0
- tobento/service-filesystem: ^1.0
Requires (Dev)
- phpunit/phpunit: ^9.5
- vimeo/psalm: ^4.0
README
使用文件创建服务,您可以轻松创建文件。
目录
入门
通过运行以下命令添加文件创建服务项目的最新版本。
composer require tobento/service-file-creator
要求
- PHP 8.0 或更高版本
亮点
- 框架无关,可以与任何项目一起使用
- 解耦设计
简单示例
以下是如何使用菜单服务的简单示例。
use Tobento\Service\FileCreator\FileCreator; use Tobento\Service\FileCreator\FileCreatorException; try { (new FileCreator()) ->content('Lorem ipsum') ->newline() ->content('Lorem ipsum') ->create('home/public/files/filename.txt', FileCreator::CONTENT_NEW); // it is ok. } catch (FileCreatorException $e) { // it failed. }
文档
文件创建器
创建方法具有以下默认参数值
use Tobento\Service\FileCreator\FileCreator; use Tobento\Service\FileCreator\FileCreatorException; try { (new FileCreator()) ->content('Lorem ipsum') ->create( file: 'home/public/files/filename.txt', handling: FileCreator::NO_OVERWRITE, modeFile: 0644, modeDir: 0755 ); // it is ok. } catch (FileCreatorException $e) { // it failed. }
以下参数可用于处理
创建方法返回一个新实例,允许以下操作
use Tobento\Service\FileCreator\FileCreator; use Tobento\Service\FileCreator\FileCreatorException; try { (new FileCreator()) ->content('Lorem ipsum') ->newline() ->content('Lorem ipsum') ->create('home/public/files/filename.txt', FileCreator::CONTENT_NEW) ->newline(num: 2) ->content('Lorem ipsum') ->create('home/public/files/filename.txt', FileCreator::CONTENT_APPEND); // it is ok. } catch (FileCreatorException $e) { // it failed. }
作者
作者接口
作者必须实现以下接口。
namespace Tobento\Service\FileCreator; /** * WriterInterface */ interface WriterInterface { /** * Write the content. * * @param resource $resource * @return void */ public function write($resource): void; }
CSV 作者
use Tobento\Service\FileCreator\FileCreator; use Tobento\Service\FileCreator\FileCreatorException; use Tobento\Service\FileCreator\Writer\Csv; $items = [ ['id' => 1, 'title' => 'cars'], ['id' => 2, 'title' => 'plants'], ]; $csvWriter = new Csv( items: $items, delimiter: ',', // default enclosure: '"', // default escapeChar: '\\', // default ); try { (new FileCreator()) ->writer($csvWriter) ->create('home/public/files/filename.csv', FileCreator::CONTENT_NEW); // it is ok. } catch (FileCreatorException $e) { // it failed. }
格式化器
Printr 格式化器
use Tobento\Service\FileCreator\FileCreator; use Tobento\Service\FileCreator\FileCreatorException; use Tobento\Service\FileCreator\Formatter\Printr; $items = [ ['id' => 1, 'title' => 'cars'], ['id' => 2, 'title' => 'plants'], ]; try { (new FileCreator()) ->content((new Printr())->format($items)) ->create('home/public/files/filename.txt', FileCreator::CONTENT_NEW); // it is ok. } catch (FileCreatorException $e) { // it failed. }