duankeng9477 2014-08-20 00:45
浏览 66

将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.

  • 写回答

2条回答 默认 最新

  • du8442 2014-08-20 01:03
    关注

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

    评论

报告相同问题?

悬赏问题

  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上