2013-03-24 56 views
6

下面的代碼說明了一切......Laravel 4:從make傳遞數據到服務提供商

// routes.php 
App::make('SimpleGeo',array('test')); <- passing array('test') 

// SimpleGeoServiceProvider.php 
public function register() 
{ 
    $this->app['SimpleGeo'] = $this->app->share(function($app) 
    { 
     return new SimpleGeo($what_goes_here); 
    }); 
} 

// SimpleGeo.php 
class SimpleGeo 
{ 
    protected $_test; 

    public function __construct($test) <- need array('test') 
    { 
     $this->_test = $test; 
    } 
    public function getTest() 
    { 
     return $this->_test; 
    } 
} 
+1

你好@schmaltz你有問題嗎?我有同樣的問題,並尋找一個解決方案,因爲我的應用程序使用類似的架構,像你的.. – Omranic 2014-02-13 05:40:23

回答

3

您需要將測試序列傳遞給該類服務提供商的內部

// NOT in routes.php but when u need it like the controller 
App::make('SimpleGeo'); // <- and don't pass array('test') 

public function register() 
{ 
    $this->app['SimpleGeo'] = $this->app->share(function($app) 
    { 
     return new SimpleGeo(array('test')); 
    }); 
} 

YourController.php

Public Class YourController 
{ 
    public function __construct() 
    { 
     $this->simpleGeo = App::make('SimpleGeo'); 
    } 
} 
+0

是的,我注意到工作。我的價值雖然不是固定的,但必須通過某種方式傳遞。例如:它在路由中可用作輸入。 – 2013-03-25 04:15:05

+0

對不起,只是注意到了這一點。可能是這樣的,你需要 http://stackoverflow.com/questions/15483542/laravel-4-way-to-inject-an-object-that-requires-configuration-into-a-controller – 2013-04-08 00:13:27

7

你可以嘗試將類綁定將參數直接放入您的應用程序容器中,如

<?php // This is your SimpleGeoServiceProvider.php 

use Illuminate\Support\ServiceProvider; 

Class SimpleGeoServiceProvider extends ServiceProvider { 

    public function register() 
    { 
     $this->app->bind('SimpleGeo', function($app, $parameters) 
     { 
      return new SimpleGeo($parameters); 
     }); 
    } 
} 

保持不變您的SimpleGeo.php。您可以在您的路線中測試它.php

$test = App::make('SimpleGeo', array('test')); 

var_dump ($test); 
+0

如果我做的應用程序::綁定像你的我得到的應用程序沒有定義。如果我保持它像我的,但添加第二個參數$參數我得到警告:缺少參數2 – 2013-03-27 17:19:15

+0

這很奇怪,對我來說正常工作。我在__/libraries__文件夾中放置了我的** SimpleGeo.php **和** SimpleGeoSeriveProvider.php **(並在composer.json文件中添加了路徑加載器,然後發出** composer dump-autoload **命令)並將** SimpleGeoServiceProvider **添加到__app/config/app.php__中的providers數組中。順便說一句,是在SimpleGeoServiceProvider.php或您的routes.php中引發的錯誤? – 2013-03-27 21:04:19

+0

嗯,我用「工作臺」命令建立了我的工作臺,所以它駐留在工作臺/中。它確實在SimpleGeoServiceProvider中引發錯誤。我要仔細檢查並回復你。 – 2013-03-27 21:49:42