Skip to content

ViToni/fortune-php

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

20 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Reader for fortune files

Implementation of a reader for fortune files in PHP.

Usage

Retrieve random fortune
use vitoni\Fortunes;

$fortunes = Fortunes::from($path);

echo $fortunes->getRandom();
Use Fortunes as (read-only) array
use vitoni\Fortunes;

$fortunes = Fortunes::from($path);

$randOffset = $fortunes->getRandomOffset();

echo $fortunes[$randOffset];
Access using an Iterator
use vitoni\Fortunes;

$fortunes = Fortunes::read($path);

foreach ($fortunes as $fortune) {
    ...
}

Over-engineered example

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).

Outputs a ready to use PHP script with Fortunes set up with a static index
php examples/indexer.php tests/_files
Static reader demo
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 appends echo $fortunes→getRandom() . "\n";

  • Pipes everything to php to execute the created script to retrieve a random fortune

Output
This is fortune 4

Other approaches

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.

Development

This project uses composer for dependency management.

Install dependencies and create autoloader script
composer install
Start minimal web server on 127.0.0.1:8000
composer run-script dev
Execute tests (indirectly with composer)
composer run-script test
Execute tests (directly with phpunit)
./vendor/bin/phpunit

Releases

No releases published

Packages

No packages published