- How do I check if a PHP value matches a ReflectionType at runtime in Laravel?
- Use `Type::accepts()` with a `ReflectionType` instance. For example, `Type::from('string')->accepts('hello')` returns `true`, while `Type::from('int')->accepts('hello')` returns `false`. Works seamlessly with Laravel’s type-hinted methods.
- Can I validate method arguments dynamically, including named parameters?
- Yes. The `Method` class supports named arguments via `accepts()`. For example, `Method::from($reflectionMethod)->accepts(foo: new Foo(), bar: new Bar())` validates arguments in any order, including nullable parameters.
- Does this package support union types like `string|int` in Laravel?
- Absolutely. Use `Type::from('string|int')->accepts(123)` or `Type::from('string|int')->accepts('text')` to validate union types. Works with PHP 8.0+ union type declarations in Laravel 8+.
- How does this integrate with Laravel’s request validation or form requests?
- Replace manual validation logic with `Type::accepts()` or `Method::accepts()` in form requests or middleware. For example, validate `$request->input('age')` against `IntType::class` instead of `is_numeric()`.
- Will this work with Laravel 10+ and PHP 8.1+?
- Yes, the package requires PHP 8.0+, but it fully supports Laravel 10+ and PHP 8.1+ features like named arguments and stricter type systems. Tested with modern Laravel versions.
- Can I use this for dynamic method dispatch (e.g., selecting handlers based on input types)?
- Yes. The `Handlers` class helps find methods that match given arguments. For example, resolve which method to call based on `Type::accepts()` checks, useful for API routing or event handlers.
- How does performance compare to `instanceof` or `is_a()`?
- Runtime checks add minimal overhead (~microseconds). Avoid in hot loops (e.g., bulk operations), but it’s negligible for most Laravel use cases like request validation or middleware.
- Does this replace PHPStan or static analysis tools?
- No. This package focuses on runtime validation, while PHPStan handles static analysis. Use both: PHPStan for compile-time checks and `better-types` for runtime assertions (e.g., in middleware or form requests).
- How do I handle custom types (e.g., my own value objects or interfaces)?
- Extend the `Type` class or use `Type::fromReflection()` with your custom `ReflectionType`. For interfaces, pass the interface class name (e.g., `Type::from('MyInterface')`). Works with Laravel’s service container proxies.
- Are there alternatives for runtime type checking in Laravel?
- Alternatives include `is_a()`, `instanceof`, or libraries like `webmozart/assert`. However, `better-types` uniquely handles union types, named arguments, and full method signature validation—ideal for modern Laravel apps.