Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get values from neon file in Nette?

Tags:

php

nette

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
like image 607
tsg Avatar asked Jun 20 '16 15:06

tsg


2 Answers

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.

like image 66
Petr 'PePa' Pavel Avatar answered Nov 15 '22 00:11

Petr 'PePa' Pavel


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.

like image 21
Jan Tojnar Avatar answered Nov 14 '22 22:11

Jan Tojnar