Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

Accesing global controller attribute from a view

Hi! I'm new with this framework, and I'm trying to get a global variable from a controller from main layout (or from the view file). Can't i do this directly without use setVar or adding a variable to "$this->view->name_var" ?

Thanks!



53.3k
Accepted
answer

Well, I think you could probably access the dispatcher from the view, then use that to get the current controller. But semantically the best way to do this is to explicitly assign the variable to the view in the controller.

edited Jul '16

What you mean by global attribute ? You can also add service to di which will return your variable.

edited Jul '16

Best option should be to pass the variable to the view as @Dylan recommended.

Your other option is to set the data into service like @Wojciech recommended. This way you will be able to access it from everywhere... model, controller, view e.t.c. You should use this option if you want to set some global variable like contact email which can be used to send email or to show in your footer e.t..c

I'm using this for setting some general configuration for my application. Short example:

// This in my Bootstrap file
$config = loadConfig();
$di->set('config', $config);

// Access in controller
$this->config->variable;

// Access in view
{{ config.variable }}

// Access in Model
$this->getDI()->getConfig()->variable;

Hi guys! Thanks for the answers. Nikolay, I use config perfectly in the views, buy what I mean is, there is a fews attributes in some controller like this:

class IndexController extends ControllerBase
{
    public $admin;
    public $mobile;
    public $auxiliar;
    public $city;
    public function beforeExecuteRoute($dispatcher)
    {


    }
    public function initialize()
    {
    }
}

In the metod initialize() I make some changes in this attributes. I think Dylan's response is what I try to do, but I thought there was a short way to access to this attributes.

Thanks to all

edited Jul '16

I think that better create some class like Profile for this, and just pass it to view maybe as class ? Less properties to handle.

Wojciech thas a really good question to ask. If I need to access to a function inside a model, with volt syntax, how can I do this?

Thanks Wojciech again!

Just:

{{ model.someFunction() }}

:)

Better to really create some class for this data beacause it looks like you can store it under class in database.