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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15595760/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 07:38:14  来源:igfitidea点击:

Laravel 4: Passing data from make to the service provider

laravellaravel-4

提问by drew schmaltz

The code below says it all...

下面的代码说明了一切......

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

回答by Antonio Frignani

You can try to bind the class with the parameters directly into your app container, like

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

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

leaving untouched your SimpleGeo.php. You can test it in your routes.php

保持您的 SimpleGeo.php 不变。你可以在你的 routes.php 中测试它

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

var_dump ($test);

回答by Juni Samos De Espinosa

You need to pass your test array to the class inside of the service provider

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

// 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

你的控制器.php

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