R - A PHP Resource Loader
Store values by key and later retrieve them, simply by calling R('the.key');
Notice - Sep 30, 2021
It is working, but I have not updated the documentation. It's available via composer now.
Retrieval
- Retrieve an instance:
R() - Retrieve a stored value:
R('stored.key') - Retrieve a list of stored values:
R('stored.key.') - Retrieve with a default backup value:
R('stored.key','defaultValue')(otherwise, an exception is thrown)
Setting
Retrieve an instance, then call the appropriate function
-
R()->set('key','value'); -
R()->set('key.subkey.another','value'); -
R()->put(['key'=>'value','key.sub'=>'value 2']) -
R()->put(['key'=>$subArray,'another'=>$anArray],'',TRUE);to also store sub-array's keys into R -
R()->put([...], 'prefix.')to prefix all set values withprefix.. The.is optional, and is appropriate for namespacing-
load&puttake prefix as 2nd arg.setdoes not take prefix
-
-
R()->load('/file-path.json', 'prefix.') - Loading dirs:
R()->loadDir($dirPath,$prefix='',$prefixWithFileNames=FALSE,$putSubArrays=TRUE,$recurse=TRUE)
Process any file type:
-
R()->setFileHandler($callable,'ext');- Like:
$callable($content,$ext)
- Like:
Install
- Copy
src/R.phpinto your project andrequire_onceit -
git clone git@github.com:ReedOverflow/PHP-Resources.git;thenrequire_oncesrc/R.php -
TODO
composer require rbear/resource
Issues
- Tests are not totally thorough.
- The README could be improved.
Old, more detailed notes
Retrieve a value
There are three ways to retrieve a value
- $theValue = R("the.key") - returns the stored value or null if nothing found
- $theValue = R("the.key","default_value") - returns the stored value or the supplied default value if nothing found
- $theValue = R("the.key.") - Returns an array of children (and the value at the.key).
For the input array ['the.key'=>'Primary','the.key.one'=>'child','the.key.two'=>'another child'],
R("the.key.) will return:
php [ '=' => 'Primary', 'one'=> 'child', 'two'=> 'another child' ]
Handling file extensions
Pass a callable and an extension or array of extensions that the function will handle.
Call R()->setFileHandler( $function, 'ext')
-
$functionreturns an array -
$functiontakes a string to be parsed into array as its first paramater -
$functiontakes a file extension as it's second paramater, where the extension always has a '.' in front of it.
Ex:
$json_decoder = function($content,$ext){
return json_decode($content,true);
};
R()->setFileHandler($json_decoder,'json');
Create your own instance
R() uses a static variable, which is one instance of the R class. You can do $z = new R() then use $z(...) just as you would have used R(...). Alternatively, you can write your own function:
function Z(...$args){
static $theObject = null;
$theObject = $theObject ?? new R();
return $theObject(...$args);
};