Love Fuel?    Donate

FuelPHP Forums

Ask your question about FuelPHP in the appropriate forum, or help others by answering their questions.
Something like Laravel's ViewComposer
  • I'm building a site that requires having user data (eg, user name) passed to every view. So I basically want the Fuel equivalent of a Laravel View Composer. 

    However, I can't seem to find one in Fuel. Am I missing it, or does this not exist? I'd rather not set the user data manually for each view in the controller, since that could become very onerous to maintain.

    I looked at Presenters, but having to create a separate presenter for each view (or do a manual override each time) seemed like the poorer alternative. 
  • So you want a global view variable?

    // for static values
    View::set_global('var', $value);

    // for variables or runtime execution
    View::bind_global('var', $value);

    Both will give you $var in every View.
  • Stupid question- where would I set these globals? Because from the documentation it looks like you set it from within a controller method if you're using view partials and want data to be available to each one. 

    In my case I just want to call this data one time and when a View is rendered it automatically knows to "do this too" (DRY) 

    Otherwise it seems like I have to call this data and pass it to the template by hand each time I render a View? 
  • They are global, so you only have to do it once. Where greatly depends on your application architecture.

    Some use the before() method of a base controller, some have an "application init" class that is always loaded in the config, some use config files directly, etc.

    In the current release version, only variables can be assigned or bound. In the latest dev version (https://raw.githubusercontent.com/fuel/core/1.8/develop/classes/view.php) you can also assign closures:

    \View::set_global('test', function() { return 'it works!'; });

    which will be available in all your views as $test.
  • Sorry for the delay in responding. I appreciate your time. 

    Given my application and the need to keep database calls to a minimum, I decided on using the relevant controller's before() to deal with it. 

    This solution doesn't win any style points. But there are only 5 controllers that actually push data to the template, so in this case it works. 
  • Agreed, definitely something to put on the agenda for v2.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

In this Discussion