dantleech/invoke

Emulate named parameters

1.0.1 2019-12-18 09:44 UTC

This package is auto-updated.

Last update: 2020-03-18 10:23:40 UTC


README

Build Status

Utility class to create new classes or invoke methods using named arguments.

PHP does not currently support named parameters, this utility provides a convienient way to emulate them.

Installation

Require with composer:

$ composer require dantleech/invoke

Why

Sometimes arguments may be sourced from arrays (e.g. user or developer configuration), having named parameters in this case can make things simpler and save time.

I probably wouldn't use this as an alternative way to create a new class when there is no reason not to use its existing construction methods.

Usage

Instantiate a new class:

<?php

use DTL\Invoke\Invoke;

class Foobar
{
    public function __construct(string $arg1, string $arg2 = 'val1')
    {
    }
}

$foo = Invoke::new(Foobar::class, [
    'arg1' => 'value1'
]);

Invoke a method:

<?php

use DTL\Invoke\Invoke;

class Foobar
{
    // ...

    public function one(string $two)
    {
    }
}

$foo = Invoke::new(Foobar::class, [
    'arg1' => 'value1'
]);

$bar= Invoke::method($foo, 'one', [
    'two' => 'bar'
]);

Alternatives

nikolaposa/cascader Utility for creating objects in PHP from constructor parameters definitions.

Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

Please make sure to update tests as appropriate.

License

MIT