brocoder / file-system
Small module for safe/unsafe work with file system.
Requires
- php: >=5.3.3
Requires (Dev)
- phpunit/phpunit: 7.1.5
This package is auto-updated.
Last update: 2024-09-19 13:32:55 UTC
README
Small module for convenient work with file system
I had aim to write intuitive and not overwhelmed module for safe*/unsafe working with file, without low-level-code-spamming in every place I need to work with file system.
* All locks in exclusive mode.
Submodules
File
General tools (all others just extends it) for safe and unsafe consistent working with file. Automatically detects three end-of-line symbols: unix (\n), mac (\r), windows (\r\n). Example:
/**
* Unsafe counter
*/
// opening the counter
$fl = new File( __DIR__ . '/counter.tmp' );
// read counter
$counter = ( int )$fl->readAll();
// writing hit
$fl->rewrite( ++$counter );
echo "Current counter value: {$fl->readAll()}";
// close counter
$fl->close();
FileLocked
Safe File implementation for consistent working with file. Example:
/**
* Fully safe counter.
*
* We open file and lock it, then reading and writing. Our counter working under continuous lock until we'll close it.
*/
// opening the counter with lock
$fl = new FileLocked( __DIR__ . '/counter_safe.tmp' );
// read counter
$counter = ( int ) $fl->readAll();
// writing hit
$fl->rewrite( ++$counter );
echo "Current safe counter value: {$fl->readAll()}";
// release counter
$fl->close();
SFile and SFileLocked
If you want just do some-single-operation with file you may don't want to deploy an object. So, you have statical implementations of File and FileLocked. Example:
SFile::append( 'test.txt', 'append text' );
echo SFile::readAll( 'test.txt' );
If you want make safe-single-manipulation, you can use SFileLocked. Next example lock the file and then safety read first line:
SFileLocked::readLine( 'test.txt', 0 );
FileMemory
This is equals to File, with the only difference - you need to call save() for apply changes (i.e. save it to file). It may be useful when you need to make many modifications with file content and you don't want to DDOS your file system saving it every time.
Example:
$fm = new FileMemory( 'test.txt' );
$fm->removeLine( 0 );
$fm->append( "sometext" );
$fm->prepend( "sometext" );
$fm->saveAndClose();
FileMemoryLocked
FileMemory with file locks.
Safety benchmark
Let's test our cool counters presented above.
Environment
Ubuntu 16.04, apache2, PHP 7.0 (FPM), Apache JMeter.
Benchmark
1000 threads per test
1 request per thread
10 tests (1000 requests per test, 10000 requests all).
In ideal case counter value must be 1000 after each test.
Results
Unsafe counter
Test 1: 1384
Test 2: 113
Test 3: 112113 (:trollface:)
Test 4: 1
Test 5: 2
Test 6: 2
Test 7: 3
Test 8: 1
Test 9: 111
Test 10: 1
Fully safe counter
Test 1: 1000
Test 2: 1000
Test 3: 1000
Test 4: 1000
Test 5: 1000
Test 6: 1000
Test 7: 1000
Test 8: 1000
Test 9: 1000
Test 10: 1000