Using a namespaced class as a View Composer in Laravel 4?

I have a simple setup where I need to show a bit of data universally across my app, in the header of my site. To do so, I have created a ComposerServiceProvider class and a HeaderComposer class to delegate this responsibility, as seen below:

ComposerServiceProvider

use IlluminateSupportServiceProvider;

class ComposerServiceProvider extends ServiceProvider {
    public function register() {
        $this->app->view->composer('templates.header', 'HeaderComposer');
    }
}

HeaderComposer

class HeaderComposer {
    public function compose($view) {

        Event::listen('illuminate.query', function($q) {
            print_r($q);
        });

        $view->with('nearbyMissions', array(
            'past' => Mission::remember(60, 'previousMissions')->previousMissions(3)->get(),
            'future' => Mission::remember(60, 'nextMissions')->nextMissions(3)->get()
        ));
    }
}

Previously, these classes were not namespaced, but I have now decided to namespace each of them as a good practice, by prepending the files with:

namespace MyProjectComposers;

However, this has broken my application as some part of my project can no longer resolve my composer classes. None of my pages work because they all use a templated header view which uses my HeaderComposer:

Class HeaderComposer does not exist (View: H:myprojectappviewstemplatesmain.blade.php)

Where am I meant to declare the use statements for my class? In my view? (Which doesn’t seem right). Somewhere else?


Source: laravel

Leave a Reply