Support the ongoing development of Laravel.io →
posted 9 years ago
IOC
Last updated 1 year ago.
0

Basically when you do a Facade, it's is assigning the Facade (MyClass), to a single instance of whatever is returned in the ServiceProvider.

Now if you did

$result = new MyClass;
$result->setAttr1(10);

$result = new MyClass;
$result->setAttr2(20);

That would give you the result you are looking for.

At least that is what I believe is happening.

Last updated 1 year ago.
0

Ok, I thought that was true ONLY if I bound it with singleton in the ServiceProvider, like this:

App::singleton('foo', function()
{
    return new FooBar;
});

Is there no smart way to return new instances using a Facade?

What I'm actually trying to do is to replicate the Eloquent style in a simple sdk for an api, like this:

MyApiSdk::someResource()->someAction()->get(); // Returns api response for GET request to someResource using someAction

Hence, MyApiSdk::someResource() just sets $this->resource to some resource and returns the object so it can be chained unit get() is called, which does the GET Curl-stuff.

The problem is the properties of the object are not reset when I make the next query to the api.

If I, however, make the calls without using Facade...

$app['myapisdk']->someResource()->someAction()->get()

...then new instances are created for each call. As intended.

Last updated 1 year ago.
0

The reason Eloquent works this way is that all of the calls such as find(), etc., are actually running new static() inside of Eloquent, thus instantiating a new instance.

When you do this via a Facade, the Facade is just pointing to the the instance that was generated when the Facade was loaded. Because what happens is that the Facade is actually a static class using __callStatic() to magically pass anything not defined in Illuminate\Support\Facades\Facade to the actual class being returned in the ServiceProvider.

Now you could write your function so that someResource() actually does the same thing, and that would do what you want.

Last updated 1 year ago.
0

Wonderful!

Thanks a lot!

Last updated 1 year ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

la-bas la-bas Joined 23 Mar 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.