Core\Env::context
Core\Env::context(): Core\Env::ContextReturns the kind of run your code is in, as a Core\Env::Context case. It never throws an error.
| Case | Your code runs | |---|---| | Request | to answer an HTTP request, or a request made with Core\Test::request | | Command | from the command line: a script, or a #[Command] method | | Isolate | in a child script started with spawn script | | Schedule | as a scheduled script from a [[schedule]] section | | Job | as one attempt of a queued job | | Test | in a #[Test] method under nvs test | | Connection | for a WebSocket or event stream connection after upgrade |
A task started with Core\Task has the same kind of run as the code that started it. A child script is Isolate, even when a request started it. A request is always Request. No header, environment variable or setting can change that.
Use it when one file does different work in different places. For example, a file can serve a page in a request and test that page when you run it from the command line.
Return value
Returns Core\Env::Context. The kind of run as a Core\Env::Context case. It is the same value for the whole run and for every task the run starts.
Examples
Print the kind of run
<?nvs// Shows how to check the kind of run the program is in.
bool $onCommandLine = Core\Env::context() == Core\Env::Context::Command;
// You run this file from the command line, so this prints `command line: yes`.echo 'command line: ', $onCommandLine ? 'yes' : 'no', "\n";command line: yesServe a page and test it
<?nvs// Shows one file that serves a page in a request and tests that page from the// command line.
if (Core\Env::context() == Core\Env::Context::Request) { // In a request, the file prints the page. echo "Welcome to the shop\n";} else { // From the command line, the file sends a request to itself and checks the answer. var $answer = Core\Test::request(Core\Http\Method::Get, '/');
// The page is the text above, so this prints `status 200` and `page ok`. echo 'status ', $answer->status(), "\n"; echo $answer->body() == "Welcome to the shop\n" ? 'page ok' : 'page wrong', "\n";}status 200page okA label for every kind of run
<?nvs// Shows a `match` with one result for each of the seven kinds of run.
class Log{ // Returns the label a log line starts with. public static function label(Core\Env::Context $context): string { return match ($context) { Core\Env::Context::Request => 'web', Core\Env::Context::Command => 'cli', Core\Env::Context::Isolate => 'child', Core\Env::Context::Schedule => 'cron', Core\Env::Context::Job => 'queue', Core\Env::Context::Test => 'test', Core\Env::Context::Connection => 'socket', }; }}
// You run this file from the command line, so this prints `[cli] order 7 saved`.echo '[', Log::label(Core\Env::context()), "] order 7 saved\n";[cli] order 7 saved