Implementation of a reader for fortune files in PHP.
use vitoni\Fortunes;
$fortunes = Fortunes::from($path);
echo $fortunes->getRandom();
use vitoni\Fortunes;
$fortunes = Fortunes::from($path);
$randOffset = $fortunes->getRandomOffset();
echo $fortunes[$randOffset];
use vitoni\Fortunes;
$fortunes = Fortunes::read($path);
foreach ($fortunes as $fortune) {
...
}
Re-reading the fortune file / directory to find all fortunes on each call might be not the best idea. In case of a MOTD this might work but for a web page this approach might not fit.
One can use the indexer
example to create a static index of all fortunes.
This index can be used as long as the files don’t change (it could be used even then when one only appends to existing files with the downside of missing out on new fortunes).
php examples/indexer.php tests/_files
php examples/indexer.php tests/_files \
| cat - <(echo 'echo $fortunes->getRandom() . "\\n";') \
| php
What the snippet does:
-
Creates a static index and prepares a Fortunes instance
-
Uses output from
indexer
and appendsecho $fortunes→getRandom() . "\n";
-
Pipes everything to
php
to execute the created script to retrieve a random fortune
This is fortune 4
One could created a static PHP readable version with the fortunes included, or something totally different.
But where would the fun be?
The original fortunes uses .dat
files which do basically the same but have a per file index.
This project uses composer for dependency management.
composer install
127.0.0.1:8000
composer run-script dev
composer
)composer run-script test
phpunit
)./vendor/bin/phpunit
-
C
-
PHP
-
Python
-
and many more…