删除存储库 类 中的 use Illuminate\Support\Facades\DB 语句

Get rid of use Illuminate\Support\Facades\DB statement in repository classes

我将 lumen 中的存储库模式与查询生成器一起使用。存储库 classes 大致如下所示:

<?php
namespace App\Repositories;

use Illuminate\Support\Facades\DB;

class RepoNameRepository {
    public function methodName() {
        /* 
        Various Calls to the DB facade...
        $data = DB::table("tableName")...->get(); 
        */
        return $data;
    }   
}

有什么有效的方法可以摆脱 use语句 use Illuminate\Support\Facades\DB 在我的每个存储库 classes 的开头?理想情况下,数据库外观将像 web.php.

中那样可用

到目前为止我能想到的是有一个带有 use 语句的 Repository base class。

不,这就是 PHP 的工作方式。

您的替代方案是使用别名:

use DB;

或者在您的调用前加上反斜杠,以便它在根命名空间中查找。

\DB::table('users');

您可以将 app() 辅助函数与 'db' service container binding key 一起使用:

$data = app('db')->table('tableName')...->get();

它不需要任何 use 语句。