PHP code example of webhappens / traverser

1. Go to this page and download the library: Download webhappens/traverser library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

webhappens / traverser example snippets


use WebHappens\Traverser\Traverser;

public $id;

/**
 * @return object|null
 */
public function parent()
{
    //
}

/**
 * @return array
 */
public function children()
{
    //
}

$traverser = Traverser::make($current);

$descendants = $traverser->descendants();

// Within a base class or trait

public function traverser()
{
    return Traverser::make($this);
}

// Within a class that extends the base class / uses the trait

$this->traverser()->descendants();

$traverser = Traverser:make($current, [
    Page::class => ['id' => 'uri'],
    Post::class => ['parent' => 'category', 'children' => 'comments'],
    Comment::class => ['parent' => 'post'],
]);

// Within AppServiceProvider.php

$this->app->bind('traverser', function () {
    return \WebHappens\Traverser\Traverser::make()->maps([...]);
});

// Within your application code

$traverser = resolve('traverser')->current($current);

// Within Category.php

public function parent()
{
    return $this->traverser()->inferParent(static::all());
}

public function children()
{
    return array_merge($this->categories(), $this->posts());
}

// Within Post.php

public function category()
{
    return $this->traverser()->inferParent(Category::all());
}

// Within Page.php

public function parent()
{
    // ...
    return new static($parentId);
}

public function children()
{
    return $this->traverser()->inferChildren(static::all());
}

$parent = $this->traverser()->parent();
$children = $this->traverser()->children();
$ancestors = $this->traverser()->ancestors();
$ancestorsAndSelf = $this->traverser()->ancestorsAndSelf();
$descendants = $this->traverser()->descendants();
$descendantsAndSelf = $this->traverser()->descendantsAndSelf();
$siblings = $this->traverser()->siblings();
$siblingsAndSelf = $this->traverser()->siblingsAndSelf();
$siblingsNext = $this->traverser()->siblingsNext();
$siblingsAfter = $this->traverser()->siblingsAfter();
$siblingsPrevious = $this->traverser()->siblingsPrevious();
$siblingsBefore = $this->traverser()->siblingsBefore();
$siblingsPosition = $this->traverser()->siblingsPosition();