dantleech/invoke
Emulate named arguments in PHP: instantiate classes or call methods by mapping associative array keys to parameter names. Validates required/missing/extra keys and type hints, throwing clear exceptions. Useful for deserialization and config loading.
Install via Composer: composer require dantleech/invoke. This lightweight utility (5 stars) fills a gap in PHP’s lack of native named parameters by enabling object construction and method invocation using associative arrays keyed by parameter names. Start by using Invoke::new() to instantiate classes from arrays (e.g., config, deserialized data) or Invoke::method() to call methods dynamically—both validate types and required arguments, throwing clear exceptions for mismatches.
Config-driven instantiation: Map configuration arrays directly to constructors:
$service = Invoke::new(Service::class, $config);
Catches missing required keys and type mismatches instead of failing silently.
Deserialization: Convert API responses or DB rows into objects without manual reflection or setters:
$user = Invoke::new(User::class, $apiResponse);
Method invocations with named arguments: Call methods cleanly when arguments are dynamic:
Invoke::method($service, 'run', ['batchSize' => 100, 'dryRun' => true]);
Integration with factories or service locators: Wrap factory logic in small classes that use Invoke internally for flexible, typed instantiation.
Testing: Use in test fixtures to instantiate entities with named defaults and partial overrides.
Performance tradeoff: Avoid in hot paths. With ~3.7μs vs ~0.08μs for direct instantiation, only use Invoke for infrequent setup (e.g., app boot, CLI, tests)—not inner loops or request-hot code.
Nullable vs required: Missing required (non-nullable) parameters throw \ArgumentCountError; missing optional params use default. Unexpected keys throw \InvalidArgumentException.
Type safety: Works only for scalar types, objects with type hints, and unions where PHP can infer a single concrete type. Complex union types (e.g. int|string|ArrayObject) may cause validation failures.
Extension point: Invoke is immutable and stateless—no configuration, just reflection. For advanced use, consider extending its introspection via ReflectionMethod/ReflectionClass if custom validation is needed.
Alternative context: If your project uses Laravel, this package is helpful for custom make() or factory logic—but for many cases, Laravel’s built-in app()->call() or explicit constructors may be clearer and faster.
Debugging tip: When exceptions say “Unexpected argument(s): 'foo'”, double-check spelling and casing—array keys must match parameter names exactly.
How can I help you explore Laravel packages today?