What is offset in Magic class

31 views
Skip to first unread message

Summer White

unread,
Apr 18, 2017, 2:29:47 AM4/18/17
to Fat-Free Framework
I really love F3's javascript notation array access and would like to build my own little class that has its own "hive" that I can use ->get("javascript.notation[example]") style notation

I think magic does this with its offset offset and the other offset functions. But not entirely sure. If so, how do I properly extend this so my get and set methods use javascript notation.

Summer White

unread,
Apr 18, 2017, 4:51:21 AM4/18/17
to Fat-Free Framework
Reading more into the code it seems that extending base would be the right way if I want to get the hive functionality.

Summer White

unread,
Apr 18, 2017, 4:54:11 AM4/18/17
to Fat-Free Framework
But then I'd be inheriting a lot more than I need. hrrmm

ikkez

unread,
Apr 18, 2017, 4:55:09 AM4/18/17
to f3-fra...@googlegroups.com
the Magic class is just an implementation of PHP's ArrayAccess interface. It's purpose is to make objects behave like arrays, which enables you i.e. to put a mapper into a foreach loop
 
foreach($mapper as $key => $value)

or use the F3 instance like an array and/or object

$f3->get('BASE')
$f3
->BASE
$f3
['BASE']

I think the JS dot notation is parsed in $f3->cut and resolved in $f3->ref
It should be possible to adapt the JS dot behaviour to your own class by using 3rd parameter of f3->ref (otherwise it'll use the HIVE as data source).

Summer White

unread,
Apr 18, 2017, 7:02:53 PM4/18/17
to Fat-Free Framework
Ah excellent suggestion by using &ref()

I noticed how F3 uses ref as a way to fetch the index of an array to set the value and thought that might be useful in my purpose but didn't see the third param.

The third param isn't documented but I can easily take a stab at it though. I'll post an example of using it once I've finished writing my class.

Summer White

unread,
Apr 19, 2017, 12:08:27 AM4/19/17
to f3-fra...@googlegroups.com
So an example would be:-

mixed &ref ( string $key [, bool $add = true, mixed $var = null ] )

Use the third argument when you want to find a reference in your own array/object instead of from the hive.

$fruitQty = ["Bananas"=>5, "Oranges"=>2, "Apples"=>42, "Mangos"=>1];
$apples = &base::instance()->ref("Apples", true, $fruitQty);
$apples = 10;

echo $fruitQty["Apples"]; // 10

I also made a PR for these additions on github
Reply all
Reply to author
Forward
0 new messages