Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>For reference, this is the <a href="https://github.com/laravel/framework/blob/v4.0.5/src/Illuminate/Container/Container.php#L126"><code>share</code> method @ v4.0.5</a>.</p> <p>So, what's happening here. I'll explain it in a couple of steps.</p> <h3>Calling The Share Method</h3> <p>As you pointed out this method is called from service providers. So, the <code>FilesystemServiceProvider</code> calls this method which looks something like this:</p> <pre class="lang-php prettyprint-override"><code>$this-&gt;app['files'] = $this-&gt;app-&gt;share(function() { return new Filesystem; }); </code></pre> <p>It's assigning the <em>return</em> value of this <code>share</code> method to a binding in the container. In a nutshell, that return value will be the new <code>Filesystem</code> instance that is returned in the closure.</p> <h3>So What Does Share Do?</h3> <p>The <code>share</code> method is just another way of defining a singleton in IoC container. All this can be a bit intimidating at first. Basically, Laravel itself is an IoC container. All the classes are bound as instances on the container. Sometimes these instances should be the <em>same</em> instance on every call.</p> <p>If you take a look at the referencing method above on GitHub, you'll notice that inside the closure a static variable is defined. It then checks if that variable is null, and if it is it resolves the closure (this is the closure that returns our new <code>Filesystem</code> instance). Then it simply returns the variable.</p> <p>Now, the next time you use <code>File::get()</code> it doesn't need to instantiate the <code>Filesystem</code> class again, because it's already been instantiated and stored in the static <code>$object</code> variable. So it simply returns the same object to you.</p> <p><strong>So!</strong> Really, you could replace the <code>$this-&gt;app['files']</code> line with this, and it would still work.</p> <pre><code>$this-&gt;app-&gt;instance('files', new Filesystem); </code></pre> <p>99% of services actually use the <code>share</code> method though because working inside a closure allows objects to be instantiated with more complex dependencies.</p> <p>Hope this helps.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload