2017 © Pedro Peláez
 

library lambda

Create closures from definition strings.

image

simones/lambda

Create closures from definition strings.

  • Sunday, August 28, 2016
  • by SimoneS
  • Repository
  • 1 Watchers
  • 0 Stars
  • 5 Installations
  • PHP
  • 0 Dependents
  • 0 Suggesters
  • 0 Forks
  • 0 Open issues
  • 1 Versions
  • 0 % Grown

The README.md

Lambda

Create closures from definition strings., (*1)

Install

composer require simones/lambda

How to use

You generate closures passing a definition string to the Lambda constructor or to Lambda::make: they will return a Lambda instance, that you can call directly (it implements the __invoke magic method) or via the call method, passing an optional array of arguments., (*2)

Defition strings format

Definitions are in the format arguments => body, borrowed from languages like Coffescript. So, for example, the following, (*3)

$increment = new Lambda('$x => $x + 1');

will translate in something like:, (*4)

$increment = function($x) { return ($x + 1); };

Multiple arguments are allowed and complex expressions can be used as the body. If the arguments part is not present, the variables x, y, z will be automatically injected and defaulted to NULL; so the above code could be written as:, (*5)

$increment = new Lmabda('$x + 1');

// or with the lambda helper

$increment = lambda('$x + 1');

// and translates to

$increment = function($x = NULL, $y = NULL, $z = NULL) { return ($x + 1); }

You're allowed to use as many parameters as wanted and arbitrary complex body definitions, though I recommend you to use mainly for short anonymous functions (I wrote this to be used with Laravel Collection's map and filter methods)., (*6)

Here's a spec case that tests the use with complex code:, (*7)

function it_allows_complex_code()
    {
        $this
            ->make('$int, $string, $array => strval($int) . strtoupper($string) . $array[0]')
            ->call([100, ' times ', ['Lambda!']])
            ->shouldBe('100 TIMES Lambda!');
    }

Limits

At this stage, no syntax check is done on the code, so you should input only trusted and well-formed definitions. It just wraps your code in a function definition, adds minor structure controls and throws exceptions when it can't do its job. I added a spec suite to test the intended behaviour, but it's my first package and I don't really feel it should be used in production as is., (*8)

Bugs and improvements

Every help is welcome to improve the package: just create a pull request., (*9)

The Versions

28/08 2016

dev-master

9999999-dev

Create closures from definition strings.

  Sources   Download

The Requires

  • php >=5.5.0

 

The Development Requires

by Simone Salerno