laravel控制器中的全局变量

时间:2015-10-05 06:20:59

标签: php laravel global-variables

我希望$year变量可用于PagesController的所有功能。我试过这段代码,但我没有成功。

class PagesController extends Controller
{
    public function __construct()
    {
        $dt = Carbon::parse();
        $year = $dt->year;
    }

    public function index()
    {
        return view('pages.index');
    }

    public function about()
    {
        return view('pages.about', compact('year'));
    }

    public function create()
    {
        return view('pages.create', compact('year'));
    }
}

3 个答案:

答案 0 :(得分:19)

<强> 1。选项:使用AppServiceProvider

在这种情况下,所有视图都可以使用$ year!

<?php

namespace App\Providers;

use Carbon;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        view()->share('year', Carbon::parse()->year);
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

<强> 2。选项:使用View Composer

在这种情况下,变量仅适用于您需要的视图。

不要忘记将新创建的提供程序添加到config/app.php

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Carbon;

class ComposerServiceProvider extends ServiceProvider
{
    /**
     * Register bindings in the container.
     *
     * @return void
     */
    public function boot()
    {
        // Using Closure based composers...
        view()->composer('pages.*', function ($view) {
            $view->with('year', Carbon::parse()->year);
        });
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

第3。使用刀片@inject-method

在需要这一年的视图中,你可以像这样注入一个Carbon实例:

@inject('carbon', 'Carbon\Carbon')

{{ $carbon->parse()->year }}

答案 1 :(得分:7)

试试这个:

//give private declaration
private $year;
public function __construct()
{
    $dt = Carbon::parse();
    $this->year = $dt->year;
}

public function index()
{
    return view('pages.index');
}

public function about()
{
    $year = $this->year;
    return view('pages.about',compact('year') );
}

public function create()
{
     $year = $this->year;
    return view('pages.create',compact('year') );
}

答案 2 :(得分:5)

您可以在事件

之前的App ::中创建全局单例
App::before(function($request) {
    App::singleton('customYear', function(){
        $dt = Carbon::parse();
        $customYear = $dt->year;
        return $customYear;
    });

    // If you use this line of code then it'll be available in any view
    View::share('customYear', app('customYear'));

    //To get the same data in any controller you may use:
    $customYear = app('customYear');
});