将DB类注入Abstract Class中的__constructor变量

Unable to inject Laravel's DB class into an abstract class located in another namespace folder.

Getting Error "Call to undefined method Illuminate\Support\Facades\DB::table()"


-Check:Working- FrontController.php

<?php
use MyProject\MainPages\Front;

    class indexController extends \BaseController {

        /**
         * @var Front
         */
        private $Front;

        /**
         * @param ProductRepository $productRepo
         */
        function __construct(Front $Front)
        {
            //Test 
            //$this->Front = $Front->goSetup();
        }
    }

-Check:Working- Front.php

<?php namespace MyProject\MainPages;

use MyProject\MainPages\NavigationSkeleton;

class Front extends NavigationBluPrint {

    /**
     * Begins the process, Step 1
     */
    protected function goSetup() {
        // $this->DB->table() etc
    }
}

-Not Working- NavigationBluPrint.php

<?php namespace MyProject\MainPages;

use \DB;

abstract class NavigationBluPrint {

    /**
     * @var DB Laravel Database connection
     */
    protected $dB;

    public function __construct(DB $dB)
    {
        // SetDB so when extended it's already set for extended classes
        $this->dB = $dB;
        // Test below
        $x = $this->dB->table('products')->get(); //Error: Call to undefined method Illuminate\Support\Facades\DB::table()
        echo '<pre>';
        print_r($x);
        echo '<pre>';
    }
}

If I need to do something with App:: to make this work, I dont understand how it's done. Thank you


Solution Found:In case someone else runs into the same problem.

In abstract class "NavigationBluPrint.php"

I replaced \DB; with=> use \Illuminate\Database\DatabaseManager as DB;

It seems to fix the problem, although I'm not sure whether its instantiating a new DB from start or using the same one. If former then it kind of defeats the purpose.

You're type hinting the facade for the DB class, not the DB class itself.

It's false the idea of using static method, via object and it is impossible.

you should create repository for your database operation then you can inject them greatly.

directions to create Eloquent repository or DB repository :

Here I found out a great article to do this.