Difference between View Composer and Creator in Laravel?

后端 未结 3 1288
既然无缘
既然无缘 2020-12-24 12:11

According to Laravel 4 documentation.

Composer is:

View composers are callbacks or class methods that are called when a view

相关标签:
3条回答
  • 2020-12-24 12:48

    Another difference is that an Exception thrown within a ViewCreator will bubble back up to the Controller. This is handy for authorizations. In the ViewCreator you can get permissions data, then if the user is not authorized for that page, throw an exception and let the controller handle it. For example:

    class MyController {
        public function MyAction {
            try {
                return view('my_view');
            } catch (\Exception $e) {
                echo "<h1>Exception</h1>";
                echo $e->getMessage();
            }
        }
    }
    
    class MyViewCreator {
        public function create(View $view) {
            $loggedInUser = User::with('permissions')->find(Auth::user()->id);
            if (! $loggedInUser->hasPermission('MY_PERMISSION')) {
                throw new \Exception("You are not authorized");
            }
            ...
        }
    }
    
    0 讨论(0)
  • 2020-12-24 12:56

    When you use View::creator you have the chance to override the variables of view in the controller. Like this:

    View::creator('layout', function($view) {
        $view->with('foo', 'bar');
    });
    
    // in controller
    return View::make('layout')->with('foo', 'not bar at all');
    
    // it's defined as 'not bar at all' in the view
    

    -

    View::composer('hello', function($view) {
        $view->with('foo', 'bar');
    });
    
    // in controller
    return View::make('hello')->with('foo', 'not bar at all');
    
    // it's defined as 'bar' in the view
    
    0 讨论(0)
  • 2020-12-24 12:57

    It took me a while to work this out, I had to dig in the source code to work it out. The difference is at what point in the cycle of the Laravel application you want the command to run.

    There are a number of points in the Laravel cycle involving views.

    You can make a view using View::make(). This is when a view is instantiated - and during the View::make() command any View::creators() are called, before the function is returned.

    Normally you just run return View::make() - which means the view is 'created', and then returned to the Laravel core where it is then 'composed' to screen. This is when the View::composer() is called (i.e. after the view has returned).

    I'm not sure why you would want to use one or the other, but that explains the difference between the two.

    0 讨论(0)
提交回复
热议问题