php - Laravel View Composer 为每个 View 复制 SQL 查询

标签 php mysql laravel laravel-5 laravel-blade

我需要在大多数 View 中访问一些数据(用户详细信息)。我做了什么:

我创建了 ComposerServiceProvider

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class ComposerServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        view()->composer(
            ['includes.header','profile'],
            'App\Http\ViewComposers\CustomerComposer'
        );

    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

创建了 CustomerComposer 类

<?php

namespace App\Http\ViewComposers;

use Illuminate\Support\Facades\Auth;
use Illuminate\View\View;
use Modules\Customers\Entities\CustomerDetail;

class CustomerComposer
{
    public $customer = [];

    /**
     * Bind data to the view.
     *
     * @param  View  $view
     * @return void
     */
    public function compose(View $view)
    {
        $user = Auth::guard('customer');

        $this->customer = CustomerDetail::where('user_id',$user->id())->first();

        $view->with( 'customer', $this->customer );
    }
}

一切正常,但是当我查看调试栏时,它显示每个 View 都执行了相同的查询,因此例如,如果我定义 ['includes.header','profile'] 如果 ['includes.header',相同的 SQL 将被执行两次','profile','something_else'] 3 次等等...

在这种情况下查询是

select * from `customer_details` where `user_id` = '1' limit 1
select * from `customer_details` where `user_id` = '1' limit 1

如果我在中提供通配符

view()->composer(
            ['*'],
            'App\Http\ViewComposers\CustomerComposer'
        );

它将生成 23 个查询!我在这里错过了什么?

最佳答案

好的,我想我找到了解决方案。在 ComposerServiceProvider 类中:

/**
* Register the application services.
*
* @return void
*/
public function register()
{
    $this->app->singleton(\App\Http\ViewComposers\CustomerComposer::class);
}

就是它。

在 Laravel 文档中

Registering A Singleton

Sometimes, you may wish to bind something into the container that should only be resolved once, and the same instance should be returned on subsequent calls into the container:

关于php - Laravel View Composer 为每个 View 复制 SQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46494897/

相关文章:

PhpStorm - 找不到要转到的声明

javascript - 无法解析从 PHP 返回的 JSON

php - SimpleSamlPHP - 生成 SP 元数据

mysql - 'unique' 列字段是否暗示了 MySQL 的索引,如果是,为什么?

Mysql列作为sql server中的vColumn语法

javascript - 预先输入建议,每个建议下方都有文字

php - 如何使用 PostgreSQL 数据库建立网站?

mysql - 为什么我在 SQL 上不断收到相同的错误消息

php - Laravel 5.5 Eloquent WhenLoaded 关系

postgresql - 多对多多态关系替代