简体   繁体   中英

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 Illuminate\Support\ServiceProvider;

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 MyProject\Composers;

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:\myproject\app\views\templates\main.blade.php)

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

Since you just namespaced your class, then you have to update your composer binding:

use Illuminate\Support\ServiceProvider;

class ComposerServiceProvider extends ServiceProvider {

    public function register() {
        $this->app->view->composer('templates.header', 'MyProject\Composers\HeaderComposer');
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM