Passing Settings to Presenters
Do you need to pass arguments to presenters that are not objects (e.g. information about whether it is running in
debug mode, directory paths, etc.) and thus cannot be passed automatically by autowiring? The solution is to encapsulate them in a
Settings
object.
The Settings
service is a very easy yet useful way to provide information about a running application to
presenters. Its specific form depends entirely on your particular needs. Example:
namespace App;
class Settings
{
public function __construct(
// since PHP 8.1 it is possible to specify readonly
public bool $debugMode,
public string $appDir,
// and so on
) {}
}
Example of registration to the configuration:
services:
- App\Settings(
%debugMode%,
%appDir%,
)
When the presenter needs the information provided by this service, he simply asks for it in the constructor:
class MyPresenter extends Nette\Application\UI\Presenter
{
public function __construct(
private App\Settings $settings,
) {}
public function renderDefault()
{
if ($this->settings->debugMode) {
// ...
}
}
}