Giter Club home page Giter Club logo

phinq's Introduction

phinq

LINQ for PHP

originally written by Tommy Montgomery

phinq is a faithful port of .NET's LINQ library (circa 4.0) to PHP.

Requirements

  • PHP 5.3 or higher

LINQ methods implemented:

  • Aggregate()
  • All()
  • Any()
  • Average()
  • Cast()
  • Concat()
  • Contains()
  • Count()
  • DefaultIfEmpty()
  • Distinct()
  • ElementAt()
  • ElementAtOrDefault()
  • Except()
  • First()
  • FirstOrDefault()
  • GroupBy()
  • GroupJoin()
  • Intersect()
  • Join()
  • Last()
  • LastOrDefault()
  • Max()
  • Min()
  • OfType()
  • OrderBy()
  • Reverse()
  • Select()
  • SelectMany()
  • SequenceEqual()
  • Single()
  • SingleOrDefault()
  • Skip()
  • SkipWhile()
  • Sum()
  • Take()
  • TakeWhile()
  • ThenBy()
  • ToArray()
  • ToDictionary()
  • Union()
  • Where()
  • Zip()

Extra methods:

  • walk()

LINQ methods to be implemented: None.

LINQ methods not implemented:

  • AsEnumerable()
  • AsParallel()
  • AsQueryable()
  • LongCount()
  • OrderByDescending() - implemented as an optional argument to orderBy()
  • ThenByDescending() - implemented as an optional argument to thenBy()
  • ToList()
  • ToLookup()

Examples

Basic Usage

//bootstrap the library, it of course uses autoload because it's not 1998 anymore
require_once 'Phinq/bootstrap.php';

//fully qualifying things sucks
use Phinq\Phinq;

//suppose you have some sort of collection
$payments = array(10.5, 11.94, 9.3, 0, 17.1, 10.5, 0);

//let's do something to it
$paymentQuery = Phinq::create($payments)
  ->where(function($payment) { return $payment !== 0; }) //non-zero
  ->orderBy(function($payment) { return $payment; }); //sorted ascending

//nothing happens until we evaluate the expressions by calling toArray()
$nonZeroOrderedPayments = $paymentQuery->toArray();
print_r($nonZeroOrderedPayments);
/*
Array
(
    [0] => 9.3
    [1] => 10.5
    [2] => 10.5
    [3] => 11.94
    [4] => 17.1
)
*/

//non-zero, ordered and distinct
print_r($paymentQuery->distinct()->toArray());
/*
Array
(
    [0] => 9.3
    [1] => 10.5
    [2] => 11.94
    [3] => 17.1
)
*/

Grouping using objects

//say we had a Person struct, and each person has a place of residence
class Person {
  public $id;
  public $name;
  public $residence;
  
  public function __construct($id, $name, State $state) {
    $this->id = $id;
    $this->name = $name;
    $this->residence = $state;
  }
}

class State {
  public $id;
  public $name;
  public $region;
  public $code;
  
  public function __construct($id, $name, $region, $code) {
    $this->id = $id;
    $this->name = $name;
    $this->region = $region;
    $this->code = $code;
  }
}
  
//...and we have these people who live in these states
$people = array(
  new Person(1, 'Tommy', new State(1, 'California', 'SW', 'CA')),
  new Person(2, 'Bobby', new State(2, 'Washington', 'NW', 'WA')),
  new Person(3, 'Joey', new State(2, 'Washington', 'NW', 'WA')),
  new Person(4, 'Jerry', new State(3, 'New York', 'NE', 'NY')),
  new Person(3, 'Dubya', new State(4, 'Texas', 'S', 'TX'))
);
  
//...and we want to group them by region
echo Phinq::create($people)
  ->groupBy(function($person) { return $person->residence->region; })
  ->select(function($grouping) { 
    //$grouping is an instance of Phinq\Grouping, which inherits from Phinq
    //it has a getKey() method which returns the key used to perform the grouping
    $obj = new stdClass();
    $obj->people = $grouping;
    $obj->region = $grouping->getKey();
    return $obj;
  })->orderBy(function($obj) { return $obj->people->count(); }, true /* descending */)
  ->aggregate(function($current, $next) { 
    $count = $next->people->count();
    return $current . sprintf(
      "%d %s (%s) live in the %s region\n",
      $count,
      $count === 1 ? 'person' : 'people',
      $next->people->aggregate(function($current, $next) {
        if ($current !== null) {
          $current .= ', ';
        }
        return $current . sprintf('%s [%s]', $next->name, $next->residence->code);
      }),
      $next->region
    );
  });

/*
2 people (Bobby [WA], Joey [WA]) live in the NW region
1 person (Dubya [TX]) live in the S region
1 person (Tommy [CA]) live in the SW region
1 person (Jerry [NY]) live in the NE region
*/

The C# equivalent would be approximately:

people
  .GroupBy(person => person.Residence.Region)
  .Select(grouping => new { Region = grouping.Key, People = grouping })
  .OrderBy(obj => obj.People.Count())
  .Aggregate((current, next) => {
    var count = next.People.Count();
    return current + string.Format(
      "{0} {1} ({2}) live in the {3} region",
      count,
      count == 1 ? "person" : "people",
      next.People.Aggregate((personString, nextPerson) {
        if (!string.IsNullOrEmpty(personString)) {
          personString += ", ";
        }

        return personString + string.Format("{0} [{1}]", nextPerson.Name, nextPerson.Residence.Code);
      }),
      next.Region
    );
  });

phinq's People

Contributors

tmont avatar nettles-jarrod avatar

Stargazers

Mihailov Vasilievic Filho avatar Sinevia avatar Zan Baldwin avatar Joe Horn avatar Kevyworks avatar Hervé  avatar Michael Clark avatar Guido Buiting avatar  avatar  avatar Paul Everton avatar  avatar Sean Goresht avatar Dawa Lama avatar Jefferson Ventura avatar Dominik Kukacka avatar Gustavo Gutiérrez avatar Junior Dias avatar  avatar Cédric Derue avatar

Watchers

 avatar James Cloos avatar Paul Everton avatar  avatar

phinq's Issues

Passing variable to ->where

Hello,

I would like to do something like that :

$nb = 5;
$status = 'pending';
$Query = Phinq::create($posts)
->where(function($post) { return $post['status'] == $status; }) // statut en cours
->take((int)$nb);

How to pass the variable $status to the where function ?

Thanks a lot,

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.