Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 4: Passing data from make to the service provider

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;
    }
}
like image 473
drew schmaltz Avatar asked Mar 24 '13 06:03

drew schmaltz


2 Answers

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

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

var_dump ($test);
like image 87
Antonio Frignani Avatar answered Sep 27 '22 22:09

Antonio Frignani


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

Public Class YourController
{
    public function __construct()
    {
        $this->simpleGeo = App::make('SimpleGeo');
    }
}
like image 20
Juni Samos De Espinosa Avatar answered Sep 27 '22 22:09

Juni Samos De Espinosa