2013-03-24 104 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