I have small application based on Nette framework.
I've created constants.neon
file and add it to container. There will be some data which should be available from presenters, models, forms etc.
How can I access to values in constants.neon
?
I know that there is a method (new \Nette\Neon\Neon())->decode([NEON_FILE_PATH])
but I don't think that this is the right way
. I suspect that after using addConfig(...)
in bootstrap.php
all data from those config files should be available all over the system.
<?php
// bootstrap.php
require __DIR__ . '/../vendor/autoload.php';
$configurator = new Nette\Configurator;
$configurator->setDebugMode(true); // enable for your remote IP
$configurator->enableDebugger(__DIR__ . '/../log');
$configurator->setTempDirectory(__DIR__ . '/../temp');
$configurator->createRobotLoader()
->addDirectory(__DIR__)
->addDirectory(__DIR__ . '/../vendor/phpoffice/phpexcel')
->register();
$configurator->addConfig(__DIR__ . '/config/config.neon');
$configurator->addConfig(__DIR__ . '/config/config.local.neon');
$configurator->addConfig(__DIR__ . '/config/constants.neon');
$container = $configurator->createContainer();
return $container;
My constants.neon
file:
constants:
DP_OPT = 'DP'
PP_OPT = 'PP'
DV_OPT = 'DV'
ZM_OPT = 'ZM'
TP_OPT = 'TP'
Thanks
UPDATE #1
Figured out that I've used wrong format of .neon
file.
constants:
DP_OPT: DP
PP_OPT: PP
DV_OPT: DV
ZM_OPT: ZM
TP_OPT: TP
To complete Jan's answer, here's how you pass your config parameters to a model.
Make your model class expect it as a constructor parameter:
namespace App\XXX;
class MyModel
{
/** @var array */
private $constants;
public function __construct(array $constants)
{
$this->constants = $constants;
}
Then register your model as a service in config (Neon):
services:
- App\XXX\MyModel(%constants%)
When you inject that model into your presenter:
class DefaultPresenter extends BasePresenter
{
/** @var App\XXX\MyModel @inject */
public $myModel;
it will automatically receive your 'constants' when instantialized.
If you store the constants inside parameters
array in the neon file, you will be able to access it from presenter’s context like this:
// $this is instance of Nette\Application\UI\Presenter
$this->context->parameters['constants']
Neon file:
parameters:
constants:
DP_OPT: DP
PP_OPT: PP
DV_OPT: DV
ZM_OPT: ZM
TP_OPT: TP
Please note that this might not be recommended approach. For more information see how to use presenter as a service.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With