域命名空间中的Laravel依赖注入

时间:2014-07-07 15:24:54

标签: php laravel-4 ioc-container

我遇到了依赖注入依赖注入的问题。我可以在构造函数中调用App :: make,并且依赖项反转工作得很好......只有当我尝试将它注入到构造函数中时才会出现问题。

ReflectionException Class StationsInterface does not exist

一个可以击中这个的uri将是... / stats / station / mogreet / 6

文件结构:

-app

    -controllers
        *StatsController

-Dashboard

    -Datasync

        -Interfaces
            *DatasyncInterface
            *MogreetDatasyncInterface

        -Services
            *MogreetDatasync

        *BackendServiceProvider
        *DatasyncBase

    -Repositories

        -Interfaces
            *CredentialsInterface
            *StationsInterface

        -Stations
            *DbCredentials
            *DbStations
            *FileCredentials

        -Stats

        *BackendServiceProvider
        *DbRepositoryBase

相关代码块如下:

服务提供商:

<?php namespace Dashboard\Repositories;

use Illuminate\Support\ServiceProvider;

class BackendServiceProvider extends ServiceProvider {

    public function register() {

        // Service Providers located in Stats directory
        $this->app->bind('StatsDailyInterface', 'Dashboard\Repositories\Stats\DbStatsDaily');
        //$this->app->bind('StatsMonthlyRepository', 'Dashboard\Repositories\Stats\DbStatsMonthly');
        //$this->app->bind('StatsYearlyRepository', 'Dashboard\Repositories\Stats\DbStatsYearly');

        // Service Providers located in Stations directory
        $this->app->bind('CredentialsInterface', 'Dashboard\Repositories\Stations\FileCredentials');
        $this->app->bind('StationsInterface', 'Dashboard\Repositories\Stations\DbStations');

    }

}

控制器:请注意,在我的构造函数中,我使用的是App :: make而不是Injecting Dependency。如果我注入依赖项,我会得到类似于DatasyncBase类的类解析错误。

<?php

use Dashboard\ConrollerFacades\Facades\Services;

class StatsController extends BaseController {

    /*
    |--------------------------------------------------------------------------
    | Stats Controller
    |--------------------------------------------------------------------------
    |
    | Pull and display stats for station, market, or corporate views
    |
    |   
    |
    */

    private $StationModel;

    public function __construct() {
        $this->StationModel = App::make('StationsInterface');
    }

    /**
    * Pulls stats for an individual station
    *
    * @param string $service of station
    * @param integer $id of station
    * 
    * @return void
    */
    public function station( $service, $stationId ) {

        $this->Service = $this->serviceSelector($service);

        if(!$this->Service) throw new Exception('Unknown Service Selected', 1);

        $this->Service->init($stationId);

        exit();

    }

    /**
    * Pulls stats for a Market
    *
    * @param integer $id of market
    *
    * @return void
    */
    public function market( $service, $marketId ) {

        $this->Service = $this->serviceSelector($service);

        if(!$this->Service) throw new Exception('Unknown Service Selected', 1);

        foreach($StationModel->getStationIdsByMarket($marketId) as $station) {
            $this->Service->init($station);
        } 

        exit();

    }

    /**
    * Pulls stats for Corporate (all stations)
    * 
    * @return void
    */
    public function corporate( $service ) {

        $this->Service = $this->serviceSelector($service);

        if(!$this->Service) throw new Exception('Unknown Service Selected', 1);

        foreach($StationModel->getAllStationIds() as $station) {
            $this->Service->init($station);
        }

        exit();

    }

    private function serviceSelector($service) {

        switch(strtolower($service)) {
            case 'brightcove': return App::make('BrightCoveDatasyncInterface'); break;
            case 'facebook': return App::make('FacebookDatasyncInterface'); break;
            case 'googleanalytics': return App::make('GoogleAnalyticsDatasyncInterface'); break;
            case 'liquidcompass': return App::make('LiquidCompassDatasyncInterface'); break;
            case 'mogreet': return App::make('MogreetDatasyncInterface'); break;
            case 'twitter': return App::make('TwitterDatasyncInterface'); break;
            default: return false; break;
        }

    }

}

此类的构造函数是发生依赖项注入问题的地方。 DatasyncBase:此类永远不会直接实例化,它由MogreetDatasync等服务类继承。将构造函数移动到MogreetDatasync类进行测试不能解决问题。

<?php namespace Dashboard\Datasync;

use Dashboard\Repositories\Interfaces\StationsInterface;
use Dashboard\Repositories\Interfaces\CredentialsInterface;

class DatasyncBase {

    protected $Station;
    protected $Credentials;

    protected $results;

    protected $stats;

    public function __construct(StationsInterface $Station , CredentialsInterface $Credentials) {
        $this->Station = $Station;
        $this->Credentials = $Credentials;
        $this->stats = array();
    }

    public function __destruct() {

        unset($this->results);
        unset($this->stats);

    }

    public function init() {}

    protected function fetch($uri = null, $post_fields = null) {

        $cURL = curl_init();
        curl_setopt($cURL, CURLOPT_URL, $uri);
        curl_setopt($cURL, CURLOPT_CUSTOMREQUEST, 'GET');
        curl_setopt($cURL, CURLOPT_POSTFIELDS, $post_fields);
        $this->results = curl_exec($cURL);
        curl_close($cURL); 

    }

}

数据同步服务:

<?php namespace Dashboard\Datasync\Services;

use Dashboard\Datasync\DatasyncBase;
use Dashboard\Datasync\Interfaces\MogreetDatasyncInterface;

class MogreetDatasync extends DatasyncBase implements MogreetDatasyncInterface {

    public function init($stationId) {}
    protected function uri() {}
    protected function parse() {}
    protected function write() {}

}

1 个答案:

答案 0 :(得分:0)

这个问题的答案是ServiceDatasyncInterfaces的闭包。以前我正在定义这样的绑定:

$this->app->bind('MogreetDatasyncInterface', 'Dashboard\Datasync\Services\MogreetDatasync');

然而,这不允许IoC以递归方式&#34;注入Inversion Dependencies,你必须使用App :: make(&#39; InversionInterface&#39;)让IoC真正正确地解决这个问题。

<?php namespace Dashboard\Datasync;

use Illuminate\Support\ServiceProvider;

use Dashboard\Datasync\Services\BrightCoveDatasync;
use Dashboard\Datasync\Services\FacebookDatasync;
use Dashboard\Datasync\Services\GoogleAnalyticsDatasync;
use Dashboard\Datasync\Services\LiquidCompassDatasync;
use Dashboard\Datasync\Services\MogreetDatasync;
use Dashboard\Datasync\Services\TwitterDatasync;

class BackendServiceProvider extends ServiceProvider {

    public function register() {

        $this->app->bind('BrightCoveDatasyncInterface', function() { return new BrightCoveDatasync( $this->app->make('StationsInterface'), $this->app->make('CredentialsInterface') ); });
        $this->app->bind('FacebookDatasyncInterface', function() { return new FacebookDatasync( $this->app->make('StationsInterface'), $this->app->make('CredentialsInterface') ); });
        $this->app->bind('GoogleAnalyticsDatasyncInterface', function() { return new GoogleAnalyticsDatasync( $this->app->make('StationsInterface'), $this->app->make('CredentialsInterface') ); });
        $this->app->bind('LiquidCompassDatasyncInterface', function() { return new LiquidCompassDatasync( $this->app->make('StationsInterface'), $this->app->make('CredentialsInterface') ); });
        $this->app->bind('MogreetDatasyncInterface', function() { return new MogreetDatasync( $this->app->make('StationsInterface'), $this->app->make('CredentialsInterface') ); });
        $this->app->bind('TwitterDatasyncInterface', function() { return new TwitterDatasync( $this->app->make('StationsInterface'), $this->app->make('CredentialsInterface') ); });

    }

}

这是一个相当小的问题,但您需要在包含正在注入的类的文件中使用正确的接口。我的DatasyncBase文件现在看起来像这样:

<?php namespace Dashboard\Datasync;

use Dashboard\Repositories\Interfaces\StationsInterface;
use Dashboard\Repositories\Interfaces\CredentialsInterface;

class DatasyncBase {

    protected $Station;
    protected $Credentials;

    protected $results;

    protected $stats;

    public function __construct(StationsInterface $Station, CredentialsInterface $Credentials) {
        $this->Station = $Station;
        $this->Credentials = $Credentials;
        $this->stats = array();
    }

    public function __destruct() {

        unset($this->results);
        unset($this->stats);

    }

    public function init() {}

    protected function fetch($uri, $post_fields = '') {

        $cURL = curl_init();
        curl_setopt($cURL, CURLOPT_URL, $uri);
        curl_setopt($cURL, CURLOPT_CUSTOMREQUEST, 'GET');
        curl_setopt($cURL, CURLOPT_POSTFIELDS, $post_fields);
        $this->results = curl_exec($cURL);
        curl_close($cURL); 

    }

}

您可以在此处找到有关ServiceProvider的更多信息: https://laracasts.com/lessons/service-providers-decoded