Download the PHP package webhappens/traverser without Composer
On this page you can find all versions of the php package webhappens/traverser. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download webhappens/traverser
More information about webhappens/traverser
Files in webhappens/traverser
Package traverser
Short Description Easily traverse nested object structures without worrying about recursion.
License MIT
Homepage https://github.com/webhappens/traverser
Informations about the package traverser
Traverser
Easily traverse nested object structures without worrying about recursion. Great for building menus, navigation, sitemaps and more!
- Installation
- Getting started
- Custom mapping names
- Inferring parent and children
- Traversal methods
Installation
Install via composer:
Import the class into your namespace:
Getting started
In order for the traverser to understand your hierarchy, you must ensure it can resolve "id", "parent" and "children" for each class in that hierarchy.
By default, it will look for "methods" or "properties" (in that order) by each of these names. If your classes extend from Illuminate\Database\Eloquent\Model
it will resolve the "id" automatically from the getKey
method.
Your classes should typically look something like this:
Next, create a new instance of the traverser class and pass in an instance of the class you'd like to use as your starting point for traversal.
You can now call the various traversal methods on this instance.
As a convenience you might want to put this on a base class or trait:
And then call it like this:
For a deeper insight on using the traverser you should take a look at the tests.
Custom mapping names
You may override the default "id", "parent" and "children" mapping names for each class if you want to.
To do this pass a second argument into the constructor containing a custom mapping array.
If you're using Laravel you may want to bind this to the Service Container.
And then resolve it like this:
Note that you can construct a new traverser instance without passing any arguments and use the maps
and current
methods instead.
Inferring parent and children
In most situations your objects will only have data about who their "parent" is or who their "children" are, not both. For this reason the traverser allows you to easily infer one from the other.
To infer parent you should pass an array of all possible parents into the inferParent
method. Each of these objects must be able to resolve its own children.
To infer children you should pass an array of all possible children into the inferChildren
method. Each of these objects must be able to resolve its own parent.
Traversal methods
Credits
- Ben Gurney: [email protected]
- Sam Leicester: [email protected]
- All Contributors
License
The MIT License (MIT). Please see License File for more information.