0

Please note that before aksing this questions I've looked into:

laravel-4 way to inject an object that requires configuration into a controller

Laravel 4: Passing data from make to the service provider

and

Laravel 4: Confused about how to use App::make()

But I cannot see that they answer my question!

Domain Model: A Site must have an Owner and currently this owner is of type Customer but can change in the future to be a Reseller or an Employee etc.. so I'm using Polymorphism as follows:

class Site has an Owner Property. Owner is an interface, Customer is a class which implements Owner, Customer has a Name and a Uid therefore these are required in the constructor of Customer.

Now I want to bind the Customer implementation to the Owner interface so that whenever I call Owner I get a Customer.

We would normally do this:

class UseCustomerAsSiteOwnerServiceProvider extends ServiceProvider{

    public function register()
    {
        $this->app->bind('hidden\Domain\Model\Site\Owner', function ($app)
        {
            return $this->app->make(new Customer());
        });


    }

}

However Customer() requires $id and $name to be initialized and these are variable objects - not static so I don't know how to pass them?

I tried this:

public function register()
    {
        $this->app->bind('hidden\Domain\Model\Site\Owner', function ($app) use ($id, $name)
        {
            return $this->app->make(new Customer($id, $name));
        });


    }

But in this case the $name and $id in the USE statement are not defined. Anyone has ideas?

UPDATE: The Customer Constructor is as follows:

    /**
     * Initialise a new Customer
     *
     * @param Identifier $id
     * @param CustomerName $name
     */
    public function __construct(Identifier $id, $name)
    {
        $this->id       =       $this->setId($id);
        $this->name     =       $this->setName($name);
    }

This will be initialized from an Aggregate root (Site). The correct types will be passed to it.

Community
  • 1
  • 1
Keith Mifsud
  • 1,599
  • 1
  • 16
  • 26
  • You are passing them into the closure correctly, they aren't defined because you never defined them before the closure. Where exactly are `$id` and `$name` coming from and what do you mean by `variable objects`? – user1669496 Apr 07 '15 at 12:56
  • @user3158900 I updated the question with more information. What I mean is that both the Id and the Name will vary in values depending on which Customer we want to initialize. The example questions i found all use static values as parameters so it's easy to use them in Service Provider. – Keith Mifsud Apr 07 '15 at 13:01

1 Answers1

0

Since I don't think it's possible to pass variables, I decided to remove the constructor from the Customer and set it's properties using custom methods so that now I can say:

$this->owner->setId(Identifier Id). The service provider will resolve Owner to its Customer implementation.

Keith Mifsud
  • 1,599
  • 1
  • 16
  • 26