PHP code example of elliotchance / iterator

1. Go to this page and download the library: Download elliotchance/iterator 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/ */

    

elliotchance / iterator example snippets


use Elliotchance\Iterator\AbstractPagedIterator;

class MyPagedIterator extends AbstractPagedIterator
{
    /**
     * The total number of items we expect to find. The last page may be partial.
     * @return integer
     */
    public function getTotalSize()
    {
        return 8;
    }

    /**
     * The number of items per page. All pages must be the same size (except the
     * last page).
     * @return integer
     */
    public function getPageSize()
    {
        return 3;
    }

    /**
     * Lazy-load a specific page.
     * @return array
     */
    public function getPage($pageNumber)
    {
        $pages = [
            [ 1, 2, 3 ],
            [ 4, 5, 6 ],
            [ 7, 8 ],
        ];
        return $pages[$pageNumber];
    }
}

$iterator = new MyPagedIterator();
echo $iterator[4]; // 5

foreach ($iterator as $item) {
    echo $item;
}
// 1 2 3 4 5 6 7 8 9

use Elliotchance\Iterator\AbstractPagedIterator;

class GithubSearcher extends AbstractPagedIterator
{
    protected $totalSize = 0;
    protected $searchTerm;
    
    public function __construct($searchTerm)
    {
        $this->searchTerm = $searchTerm;
        
        // this will make sure totalSize is set before we try and access the data
        $this->getPage(0);
    }
    
    public function getTotalSize()
    {
        return $this->totalSize;
    }

    public function getPageSize()
    {
        return 100;
    }

    public function getPage($pageNumber)
    {
        $url = "https://api.github.com/search/repositories?" . http_build_query([
            'q' => 'fridge',
            'page' => $pageNumber + 1
        ]);
        $result = json_decode(file_get_contents($url), true);
        $this->totalSize = $result['total_count'];
        return $result['items'];
    }
}

$repositories = new GithubSearcher('fridge');
echo "Found " . count($repositories) . " results:\n";
foreach ($repositories as $repo) {
    echo $repo['full_name'];
}