We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

How to define a config variable in phalcon?

I want a config variable which is accessible in all volt views. In the variable I want to store a static path which can be changed later on. So how can I do this?

e.g I want a variable with the name $IMGIXImagesPath = 'mydomain-images.imgix.net';

Then it should be accessible in all volt views

e.g in volt I want to access it like

{{ IMGIXImagesPath ~ image-name.png }}

Thanks



125.7k
Accepted
answer
edited Sep '19

How will this variable be changed? Will it be changed programmatically or just something you want to be able to change like you would any other configurable variable?

You could define it in a constant, then in Volt:

{{ constant('IMGIXIMAGESPATH') }}image-name.png

Or you could add it to your app's config ( https://docs.phalcon.io/3.4/en/config ), then add that config to your DI, which will make it natively accessible in your view:

{{ config.imgix_images_path }}image-name.png

Or, you could simply add it to your View in your bootstrap code when it's defined:

$DI->set('view',function() use($Config,$DI){
    $DI = \Phalcon\DI::getDefault();
    $View = new \Phalcon\Mvc\View();
    $View->setViewsDir($Config->dirs->views);
    $View->registerEngines(['.phtml'=>$DI->get('volt',[$View,$DI])]);

    $View->imgix_images_path = $Config->imgix_images_path;
    return $View;
});
{{ img_images_path }}image-name.png

Personally I'd put it in the app's config and reference it that way.