The Environment object encapsulates the $_SERVER
superglobal array and decouples the Slim application from the PHP global environment. Decoupling the Slim application from the PHP global environment lets us create HTTP requests that may (or may not) resemble the global environment. This is particularly useful for unit testing and initiating sub-requests. You can fetch the current Environment object anywhere in your Slim application like this:
$container = $app->getContainer();
$environment = $container['environment'];
Each Slim application has an Environment object with various properties that determine application behavior. Many of these properties mirror those found in the $_SERVER
superglobal array. Some properties are required. Other properties are optional.
application/json;charset=utf8
)$_SERVER
superglobal array. If present, these values must retain the “HTTP_” prefix.Authentication
header’s decoded username.Authentication
header’s decoded password.Authentication
header as sent by the HTTP client.Authentication
header’s authentication type (e.g., “Basic” or “Digest”).\Psr\Http\Message\UploadedFileInterface
(for example, native Slim Framework \Slim\Http\UploadedFile
)Each Slim application instantiates an Environment object using information from the current global environment. However, you may also create mock environment objects with custom information. Mock Environment objects are only useful when writing unit tests.
$env = \Slim\Http\Environment::mock([
'REQUEST_METHOD' => 'POST',
'REQUEST_URI' => '/foo/bar',
'QUERY_STRING' => 'abc=123&foo=bar',
'SERVER_NAME' => 'example.com',
'CONTENT_TYPE' => 'multipart/form-data',
'slim.files' => [
'field1' => new UploadedFile('/path/to/file1', 'filename1.txt', 'text/plain', filesize('/path/to/file1')),
'field2' => new UploadedFile('/path/to/file2', 'filename2.txt', 'text/plain', filesize('/path/to/file2')),
],
]);