Laravel 4:将数据从make传递给服务提供商

Laravel 4:将数据从make传递给服务提供商,laravel,laravel-4,Laravel,Laravel 4,下面的代码说明了一切 // 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

下面的代码说明了一切

// 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;
    }
}
//routes.php
应用程序::make('SimpleGeo',array('test');应用程序['SimpleGeo']=$this->app->share(函数($app)
{
返回新的SimpleGeo($what_goes_here);
});
}
//SimpleGeo.php
SimpleGeo类
{
保护$u检验;
公共函数uu构造($test)_test=$test;
}
公共函数getTest()
{
返回$this->\u测试;
}
}

您需要将测试数组传递给服务提供商内部的类

// 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'));
    });
}

您可以尝试将带有参数的类直接绑定到应用程序容器中,如

<?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);
        });
    }
}

是的,我注意到这很有效。但我的值不是静态的,必须以某种方式传递。例如:它在Route中可用作输入。抱歉,刚刚注意到了这一点。可能是这样的东西,如果我做应用程序::绑定像你的我得到应用程序没有定义。如果我像我的一样保留它,但添加第二个参数$parameters,我会得到警告:缺少参数2这很奇怪,对我来说工作正常。我已将SimpleGeo.php和SimpleGeoSeriveProvider.php放在/libraries文件夹中(并在composer.json文件中添加了路径加载器,然后发出composer dump autoload命令),并将“SimpleGeoServiceProvider”添加到app/config/app.php中的providers数组中。顺便说一句,这个错误是在simplegoserviceprovider.php还是在routes.php中产生的?我使用“workbench”命令构建了我的错误,因此它位于workbench/中。它确实会在SimpleGoServiceProvider中抛出错误。我会再核实一下,然后再给你回复。你好@schmaltz你的问题有答案了吗?我遇到了同样的问题,正在寻找解决方案,因为我的应用程序使用了与您类似的体系结构。。
<?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);
        });
    }
}
$test = App::make('SimpleGeo', array('test'));

var_dump ($test);