Hello everyone,
how can i define a global constant in Laminas, so that I can retrieve the data across modules or views site wide.
define('SITE_NAME','Website name');
how is this possible with laminas?
Hello everyone,
how can i define a global constant in Laminas, so that I can retrieve the data across modules or views site wide.
define('SITE_NAME','Website name');
how is this possible with laminas?
Constants can be defined any time before they are accessed. As such, you could do so in your public/index.php
, config/autoload/*.php
files, etc.
We generally recommend against using global constants, however, as it couples your application to global state. A better approach is to define a variable in your configuration, and then inject that value into the services that require it. It takes a little more work, but makes testing easier, and tends to prevent errors due to failure to define the constants.
Thanks @matthew is there an example to implement the second approach?
As an example, your config/autoload/local.php
might include:
return [
'site_name' => 'Website Name',
];
From there, a factory can pull that value from the config to inject in the instance it is creating:
class SiteHelperFactory
{
public function __invoke(ContainerInterface $container)
{
return new SiteHelper($container->get('config')['site_name']);
}
}
I have created a config file using the first approach.
How do I get these configurations in my view or controller?
For your controller, inject them via the controller’s factory, as I demonstrated with the SiteHelperFactory
above.
For your view, you’ll need to pass them to your view model. So, pass them to your controller, and then in your controller, when injecting your view model or returning view models, include the value:
// Injecting the view model:
$this->getEvent()->getViewModel()->site_name = $this->siteName;
// Returning data for a view model:
return [
'site_name' => $this->siteName,
];
Thanks @matthew mixing your idea and this code example helped me achieved the result required.