laminas: application wide access of variables from config files

1.7k views Asked by At

i'm on this for several hours. i'm looking for a way to access easily application wide variables from config files. i've read under https://discourse.laminas.dev/t/define-global-constant-for-use-site-wide/1455 that constants are not a good way.

on Zend framework - get config inside controller its being said that i have to create a factory and pass the variables when instantiate the controller in the factory and from there i have to inject it to the view model or other classes.

but seriously this doesnt seem for me to be the best way. for example if i want to access a variable that i have stored in global.php or application.config.php i have to write 10-15 lines of code, create factorys etc. until i finally can access it ?

is there no more easy way ?

2

There are 2 answers

0
Guillaume Pagnard On

It doesn't necessarily take 10-15 lines of code, one line of code plus one line of configuration could be enough for this purpose.

In the Factory method that instanciate your Controller object a single line that can retrieve a configuration variable value could look like :

$my_config_value = $container->get('config')['my_config_variable_name'];

This variable must have been declared and initialized in a configuration somewhere, for example in a config/autoload/yourmodulename.php configuration file with a line inside the returned configuration array that look like this :

'my_config_variable_name' => 'mys3containerpath.com/xxx',
0
Błażej Kowalczyk On

You do not have to write custom factory. With LazyControllerAbstractFactory config will be passed to constructor parameter with type array

// module.config.php
use Laminas\Mvc\Controller\LazyControllerAbstractFactory;
return [
// ...
'controllers' => [
        'abstract_factories' => [
            LazyControllerAbstractFactory::class,
        ],
    ],
];
SomeController class extends AbstractActionController
{
  private $configParam,$model;
  public function __construct(ModelClass $model,array $config)
  {
    $this->model=$model;
    $this->configParam=$config['paramName'];
  }
  public function indexAction()
  {
    return ['param'=>$this->configParam];
  }
}

The same rule applies to ReflectionBasedAbstractFactory.