Novactive / NovaCollection

Collection implementation that wraps regular PHP arrays.
MIT License
9 stars 3 forks source link

The collection factory - strategy / factory method implementation #4

Open nozavroni opened 7 years ago

nozavroni commented 7 years ago

@Plopix: I was thinking about how the factory should work, what it should be capable of, and what its interface should look like and I think I may be onto something. Wanted to get your input.

Basically, the way I see the factory working, it would use the strategy pattern and the factory method pattern to abstract away all the collection instantiation details from the user, while allowing the developer (us) enormous flexibility in how collections are generated (and from what/where).

I think the best way to describe what I'm talking about is through code. So here we go...

// anything invokable can be a strategy
$csvStrategy = new Strategy\CSV();
Factory::registerStrategy($csvStrategy, 'CSV');

// including anonymous functions
Factory::registerStrategy(function($data) {
    return new Collection(explode(",", $data));
}, 'Explode');

Factory::registerStrategy(function($data) {
    return new Collection(str_split($data));
}, 'StrSplit');

Factory::registerStrategy(function($data) {
    return new Collection(json_decode($data));
}, 'JsonDecode');

$collection = Factory::create($data, 'JsonDecode');

There would probably need to be built-in factory strategies for building collections from xml, json, csv, sql queries, ez result sets, yaml, html tables, php arrays, and anywhere else we may expect a collection of items to come from.