- How do I install hyperf/macroable in a Hyperf project?
- Run `composer require hyperf/macroable` in your project directory. The package integrates seamlessly with Hyperf’s DI container and requires no additional configuration. Ensure your Hyperf version is 2.0+ for full compatibility.
- Can I use Laravel’s macro syntax (e.g., Str::macro()) in Hyperf with this package?
- No, this package mirrors Laravel’s macroable trait but is tailored for Hyperf. Use `YourClass::macro('name', fn() => ...)` instead. For string helpers, create a custom class or extend Hyperf’s `Stringable` trait.
- Will macros work with Hyperf’s coroutines (go functions)?
- Yes, macros can be designed to work with coroutines. For async macros, wrap the logic in `go(fn() => $macro())` or use Hyperf’s `AsyncQueue` for background execution. Test thoroughly in coroutine contexts.
- Does this package support Hyperf’s DB query builder macros like Laravel’s?
- Yes, you can extend Hyperf’s query builders (e.g., `Model::query()->macro('byStatus', fn($query) => ...)`). The package integrates with Hyperf DB’s fluent query interface, just like Laravel’s Eloquent.
- Is hyperf/macroable stable for production, or should I avoid it?
- The package is production-ready, but pin to `v3.1.x` to avoid beta risks. It’s actively maintained and aligns with Hyperf’s architecture. Monitor Hyperf’s roadmap for native macro support that might replace this package long-term.
- How do I test macros in PHPUnit with Hyperf?
- Mock macro invocations using PHPUnit’s `getMockBuilder()` or `partialMock()`. For async macros, test with Hyperf’s `AsyncQueue` context or `Context::save()`. Example: `$mock = $this->getMockBuilder(YourClass::class)->onlyMethods(['macro'])->getMock();`
- Can I use this package to migrate macros from Laravel to Hyperf?
- Yes, but rewrite macros for Hyperf-specific logic (e.g., replace `Str::macro()` with a custom class). Avoid mixing Laravel’s `macroable` and this package in the same codebase to prevent conflicts.
- What’s the performance impact of using macros in Hyperf?
- Macros add ~5–10ms per call due to dynamic method lookup, which is negligible for most use cases. For high-frequency services, benchmark against manual methods or Hyperf’s decorators or AOP.
- How do I register macros globally in Hyperf’s container?
- Use Hyperf’s `Container::get()` to access the container and register macros in a `BootServiceProvider`. Example: `Container::get(YourClass::class)->macro('name', fn() => ...)`. Ensure bindings align with Hyperf’s singleton/context model.
- Are there alternatives to hyperf/macroable for Hyperf projects?
- Consider Hyperf’s native decorators or `hyperf/aop` for cross-cutting concerns with less overhead. Decorators are lighter for middleware/logging, while AOP offers aspect-oriented programming. Macros excel for fluent, reusable domain logic.