依赖注入 - 调用未定义的方法 - Laravel 4

时间:2014-01-22 15:32:13

标签: php dependency-injection laravel-4 ioc-container

我有一个Facade播放器,我在其中设置了一个功能信息,这个函数会给我玩家的信息,我的问题是当我通过依赖注入调用该函数时它会给我一个错误:

调用未定义的方法Team \ Player \ Facades \ Player :: info()

相反,如果我调用该函数执行Player::info();它工作!为什么有依赖性会把这个错误扔给我?

跟随我的班级球员

class Player {

use Team\Player\Models\User;
use Team\Player\Models\Team;
use Team\Player\Models\Fighter;

  public function info($user_id)
  {
    return Fighter::with('team','user')->where('player_id','=',$user_id)->first();
  }

}

我的控制器,我尝试呼叫依赖

class MatchController extends BaseController {

    protected $match;
    protected $player;

    function __construct(Match $match,Player $player) { // dependency injection
        $this->match = $match;
        $this->player = $player;
    }

    public function getInfoPlayer() 
    {
        $player_id = Input::get('user_id');
        $player = $this->player->info($player_id);
        return View::make('site/team/event/scripts/infoPlayer')->withPlayer($player);
    }


}

和我绑定班级的服务提供商

public function register()
    {

         $this->app['player'] = $this->app->share(function($app)
      {
        return new Player;
      });

         $this->app->booting(function()
        {
          $loader = \Illuminate\Foundation\AliasLoader::getInstance();
          $loader->alias('Player', 'Team\Player\Facades\Player');
        });
    }

1 个答案:

答案 0 :(得分:3)

您没有显示所有名称空间,并使用您的文件中存在冲突的子句。

但我可以根据你给我们的内容做一点猜测:

如果你收到

 Call to undefined method Team\Player\Facades\Player::info()

当你这样做时

$player = $this->player->info($player_id);

是因为

function __construct(Match $match, Player $player) { // dependency injection
}

以某种方式告诉Laravel实例化

Team\Player\Facades\Player

而不是使用已经实例化的:

Team\Player\Player

哪个是

$this->app['player'];

所以,有一种可能性就是

uses Team\Player\Facades\Player;

MatchController课程中。你应该在哪里

use Player;

use Team\Player\Player;

但这会让Laravel注入Team\Player\Player而不是$this->app['player']的新实例,为此,你必须

function __construct(Match $match, PlayerInterface $player) {}

然后

App::bind('PlayerInterface', function($app) {
    return $app['player'];
});

嗯......就是这样。

修改

你必须创建那个界面,因为PHP会抱怨没有找到它。

放置此绑定的最佳位置是在其自己的'app / bindings.php'文件中,但您必须将其加载到app/start/global.php中:

require app_path().'/filters.php';
require app_path().'/bindings.php';

您的控制器应如下所示:

uses Team\Player\PlayerInterface;

class MatchController extends BaseController {

    ...

    function __construct(Match $match, PlayerInterface $player) 
    {
       ...
    }

    public function getInfoPlayer() 
    {
       ...
    }

}

You Player类必须实现该接口:

class Player implements PlayerInterface {

    ...

}