Skip to content

Sequence Tutorial

Jason Dent edited this page Sep 1, 2015 · 6 revisions

Sequence Tutorial

Introduction

The idea behind this tutorial is to provide a simple introduction to using the Sequence class and the respective functions.

The Sequence library works in a declarative style vs the foreach imperative style.
If you are not used to programming in this way, Sequence can take a bit of getting used to.

Code Samples

All code samples and data can be found here: Tutorial Code

Installing Sequence

Composer

To install Sequence via composer, add the following revinate/sequence to your composer.json file.

"repositories": [
    {
        "name": "revinate/sequence",
        "type": "vcs",
        "url": "https://github.com/revinate/sequence"
    }
],
"require": {
    "revinate/sequence": "~0.3"
},

Using Sequence in your source code

To get the most out of the Sequence library, include the follow use statements at the top of your files:

use Revinate\Sequence\Sequence;
use Revinate\Sequence\fn as fn;

Loops

In many cases, Sequence can be used as a replacement for foreach loops.

Employee Example

The easiest way to learn to use Sequence is to see code examples.

Sample JSON Data

{"employees":[
  {"firstName":"John", "lastName":"Doe", "employeeId":42, "dateOfBirth":"1975-05-22"},
  {"firstName":"Anna", "lastName":"Smith", "employeeId":35, "dateOfBirth":"1989-02-01"},
  {"firstName":"Peter", "lastName":"Jones", "employeeId":48, "dateOfBirth":"1992-02-28"},
  {"firstName":"Paula", "lastName":"Johnson", "employeeId":212, "dateOfBirth":"1992-03-28"},
  {"firstName":"Paul", "lastName":"Jones", "employeeId":143, "dateOfBirth":"1992-11-03"},
  {"firstName":"Liz", "lastName":"Tyler", "employeeId":53, "dateOfBirth":"1982-05-05"},
  {"firstName":"Tim", "lastName":"Jones", "employeeId":22, "dateOfBirth":"1991-06-18"},
  {"firstName":"Mary", "lastName":"Cortes", "employeeId":130, "dateOfBirth":"1980-05-03"}
]}

Example foreach

// Get a list of employees foreach
$names = array();
foreach ($employees as $employee) {
    $names[] = $employee['firstName'];
}
print_r($names);

Example Sequence

// Using a sequence
$names2 = Sequence::make($employees)    // construct a sequence
    ->pluck('firstName')                // extract the value from 'firstName'
    ->to_a();                           // convert it back into an array.

print_r($names2);

Output Both code snippets will have the same output:

Array
(
    [0] => John
    [1] => Anna
    [2] => Peter
    [3] => Paula
    [4] => Paul
    [5] => Liz
    [6] => Tim
    [7] => Mary
)

Sequence Explained

Statement Explanation
Sequence::make($employees) this will create a Sequence object out of the $employees array.
->pluck('firstName') extract the field called firstName from the employee record.
->to_a(); convert the Sequence back into an array.