hyperf/docs/en/utils.md

48 lines
1.9 KiB
Markdown
Raw Normal View History

2021-05-09 15:37:29 +08:00
# Utils
2019-06-04 19:29:07 +08:00
2021-05-09 15:37:29 +08:00
Hyperf provides a large number of convenient utils. Some commonly used and useful ones but not all of them are listed in this section. For more details, please refer [hyperf/utils](https://github.com/hyperf/utils).
2019-06-04 19:29:07 +08:00
2021-05-09 15:37:29 +08:00
## Coroutine Util
2019-06-04 19:29:07 +08:00
### Hyperf\Utils\Coroutine
2021-05-09 15:37:29 +08:00
This util is used to assist in the judgment or operation of the coroutine.
2019-06-04 19:29:07 +08:00
2019-06-04 19:30:50 +08:00
#### id(): int
2019-06-04 19:29:07 +08:00
2021-05-09 15:37:29 +08:00
Get current `coroutine ID` by using static method `id()`. If it is not under the coroutine environment return `-1`.
2019-06-04 19:29:07 +08:00
2019-06-04 19:30:50 +08:00
#### create(callable $callable): int
2019-06-04 19:29:07 +08:00
2021-05-09 15:37:29 +08:00
The static method `create(callable $callable)` can be used to create a coroutine. It can also be done by using global method `co(callable $callable)` and `go(callable $callable)`. The `create(callable $callable)` method is an encapsulation of the creation method in `Swoole`. The difference is that it will not throw out uncaught exceptions, which will be thrown by `Hyperf\Contract\StdoutLoggerInterface` as `warning` exceptions.
2019-06-04 19:29:07 +08:00
2019-06-04 19:30:50 +08:00
#### inCoroutine(): bool
2019-06-04 19:29:07 +08:00
2021-05-09 15:37:29 +08:00
`inCoroutine()` is a static method to determine whether it is currently in a coroutine environment.
2019-06-04 19:29:07 +08:00
### Hyperf\Context\Context
2019-06-04 19:29:07 +08:00
The `Context` is used to handle coroutine context. It is basically an encapsulation of `Swoole\Coroutine::getContext()`. However, the `Hyperf\Context\Context` is compatible with running in a non-coroutine environment.
2021-05-09 15:37:29 +08:00
### Hyperf\Utils\Coordinator\CoordinatorManager
The `CoordinatorManager` is used to schedule the coroutine when events occurred.
```php
<?php
use Hyperf\Coordinator\CoordinatorManager;
use Hyperf\Coordinator\Constants;
use Hyperf\Coroutine\Coroutine;
2021-05-09 15:37:29 +08:00
Coroutine::create(function() {
// Invoked after all OnWorkerStart event callbacks are completed
CoordinatorManager::until(Constants::WORKER_START)->yield();
echo 'worker started';
// Assigning resources
// Invoked after all OnWorkerStart event callbacks are completed
CoordinatorManager::until(Constants::WORKER_EXIT)->yield();
echo 'worker exited';
// Recycling resources
});
```