dream543211 2014-05-18 15:42
浏览 24
已采纳

使用Laravel View Composer类

I have created the class composer, please where can i register it on the application is it the global.php or where

class UserComposer
{
    public function __construct(Sentry $user)
    {
        $this->user = $user;
    }

    public function currentUser()
    {
        return $this->user->getUser();
    }
    public function compose($view)
    {
        $view->with('name', $this->currentUser()->first_name);
    }
}

please where will i registered it?

  • 写回答

1条回答 默认 最新

  • dove2199 2014-05-19 13:51
    关注

    There are two ways you could do this

    1. Using your start files

    you could register it in app/start/global.php

    From the laravel docs

    Your application's start files are stored at app/start. By default, three are included with > your application: global.php, local.php, and artisan.php.

    But I prefer using the global.php for including other files so as not to populate the global.php

    In this context (registering view composers), you could create a file 'app/composers.php' and include it in your global.php file like so:

    require app_path() . '/composers.php';
    

    2. Using Service Providers

    Create a service Provider. (Sample code below)

    class ComposerServiceProvider extends ServiceProvider
    {
        public function register()
        {
            $this->registerUserComposer();
        }
    
        protected function registerUserComposers()
        {
            $this->app['view']->composers([
                'UserComposer@currentUser' => [
                    'view1', 'view2'
                ],
            ]);
        }
    }
    

    Then add an entry into the 'providers' array of your app/config/app.php

    'providers' => array(
        ....
    
        'ComposerServiceProvider'
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100