PHP Map

303c2b37c0e83e752cbc15c7feb022b8?s=47 Aimeos
September 04, 2020

PHP Map

Easy to use and elegant handling for PHP arrays using Map objects

303c2b37c0e83e752cbc15c7feb022b8?s=128

Aimeos

September 04, 2020
Tweet

Transcript

  1. PHP Array > Map

  2. Aimeos E-Commerce framework

  3. Why?

  4. $list = [ ['id' => '1', 'value' => 'value1'], ['id'

    => '2', 'value' => 'value2'], null ]; Starting point
  5. $list[] = ['id' => '3', 'value' => 'value3']; unset($list[0]); $list

    = array_filter($list); sort($list); $pairs = array_column($list, 'value', 'id'); $value = reset($pairs) ?: null; Current way
  6. Solutions

  7.  Laravel collections  CakePHP collections  Arrayy  Underscore.php

    (ceased) Others
  8. php-map.org

  9. $value = map( $list ) ->push(['id' => '3', 'value' =>

    'value3']) ->remove(0) ->filter() ->sort() ->col('value', 'id') ->first(); Using Map
  10. $map[] = ['id' => '3', 'value' => 'value3']; $value =

    $map[0]; count($map); foreach($map as $key => value) {} Still possible
  11. More than array

  12.  map()  new Map()  Map::from() Creating maps 

    map([1, 2, 3])  map(new Map())  map($iterator)  map('abc')
  13. Almost all array methods supported Array methods

  14.  concat()  collapse()  duplicates()  flat()  countBy()

     groupBy() Additional methods  except()  only()  pull()  take()  skip()  ...
  15.  each()  every()  nth()  pipe()  some()

     ... Accepting closures
  16. $map->each( function( $val, $key ) { echo $key . ':

    ' . $val; } ); Closure example
  17.  concat()  every()  find()  flat()  includes()

     join()  keys() Like Javascript  map()  pop()  push()  reduce()  reverse()  some()  ...
  18. Useful methods map([1,2,3])->join(','); // '1,2,3' Map::split('1,2,3'); // map([1,2,3]) map(['a'=>1,'b'=>2])->toUrl(); //

    'a=1&b=2' map(['a'=>1,'b'=>2])->toJson(); // '{"a":1,"b":2}'
  19. Fluent interface $map->push( 'value' ) ->remove( 0 ) ->filter() ->sort();

  20. $e = new \RuntimeException('not found'); map([])->first($e); Find or fail

  21. Map::method( 'strrev', function($sep) { return strrev(join($sep, $this->list)); } ); Map::from(['c',

    'b', 'a'])->strrev(' > '); // returns 'a > b > c' Custom methods
  22. jQuery style

  23. class MyClass { private $code; private $status = 0; public

    function __construct( $code ) { $this->code = $code; } public function setStatus( int $s ) { $this->stat = $s; return $this; } public function getCode() { return $this->code; } } Example class
  24. $objects = Map::from( [ 'a' => new MyClass( 'x' ),

    'b' => new MyClass( 'y' ) ] ); Example Map
  25. $result = $objects ->setStatus(1) ->getCode() ->toArray(); Operations on objects

  26. // status of all object is 1 // $result contains:

    ['a' => 'x', 'b' => 'y'] Result
  27. ?

  28. Aimeos php-map.org Twitter: @aimeos facebook.com/Aimeos