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

时间:2013-03-24 06:17:39

标签: 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 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;
    }
}

2 个答案:

答案 0 :(得分: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。您可以在routes.php

中测试它
$test = App::make('SimpleGeo', array('test'));

var_dump ($test);

答案 1 :(得分: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');
    }
}