https://github.com/dantleech/invoke
Utility to invoke class methods using named parameters
https://github.com/dantleech/invoke
Last synced: about 1 year ago
JSON representation
Utility to invoke class methods using named parameters
- Host: GitHub
- URL: https://github.com/dantleech/invoke
- Owner: dantleech
- Created: 2019-12-07T10:55:45.000Z (over 6 years ago)
- Default Branch: master
- Last Pushed: 2021-12-02T21:57:12.000Z (over 4 years ago)
- Last Synced: 2025-03-27T15:13:13.386Z (over 1 year ago)
- Language: PHP
- Size: 81.1 KB
- Stars: 5
- Watchers: 1
- Forks: 2
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
Awesome Lists containing this project
README
Invoke
======
[](https://travis-ci.org/dantleech/invoke)
Utility class to create new classes or invoke methods using named arguments.
PHP does not currently support [named
parameters](https://wiki.php.net/rfc/named_params), this utility provides a
convenient way to emulate them.
Installation
------------
Require with composer:
```bash
$ composer require dantleech/invoke
```
Why
---
Sometimes arguments may be sourced from arrays e.g. for "deserialization" or
instantiating configuration nodes).
Validating the existence of array keys, checking their types etc. is error
prone and time consuming.
By using `Invoke::new(MyObject::class, $array)` you can map the array keys
directly to the `__construct` parameters.
This library will, throw descriptive exceptions:
- If there are extra keys.
- If there are missing required keys (i.e. non-nullable values).
- If the types are wrong.
Performance
-----------
`Inoke::new(Class::class, [])` is around 50x slower than `new Class()`, or
260,000 operations per second vs. ~13,000,000.
```
+--------------------------+---------+
| subject | mode |
+--------------------------+---------+
| benchInvokeNewClass | 3.720μs |
| benchInstantiateNewClass | 0.076μs |
+--------------------------+---------+
```
Usage
-----
Instantiate a new class:
```php
'value1'
]);
```
Invoke a method:
```php
'value1'
]);
$bar= Invoke::method($foo, 'one', [
'two' => 'bar'
]);
```
Alternatives
------------
[nikolaposa/cascader](https://github.com/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](https://choosealicense.com/licenses/mit/)