Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5: app() helper function

Tags:

html

php

laravel

Why should someone use this:

function flash($title)
{
    $flash = app('App\Http\Flash');

    return $flash->message('This is a flash message');
}

over this:

use App\Http\Flash;

function flash($title)
{
    $flash = new Flash;

    return $flash->message('This is a flash message');
}

In the first case we are getting the available container instance.

In the second case we load the Flash class and instantiate it then in our flash method.

I've seen someone use the first approach and I wonder if there is ANY difference in using the second approach.

like image 885
LoveAndHappiness Avatar asked Oct 09 '15 01:10

LoveAndHappiness


1 Answers

If you are using it as in your example - you'll get no profit. But Laravel container gives much more power in this resolving that you cannot achieve with simple instantiating objects.

  1. Binding Interface - you can bind specific interface and it's implementation into container and resolve it as interface. This is useful for test-friendly code and flexibility - cause you can easily change implementation in one place without changing interface. (For example use some Countable interface everywhere as a target to resolve from container but receive it's implementation instead.)
  2. Dependency Injection - if you will bind class/interface and ask it as a dependecy in some method/constructor - Laravel will automatically insert it from container for you.
  3. Conditional Binding - you can bind interface but depending on the situation resolve different implementations.
  4. Singleton - you can bind some shared instance of an object.
  5. Resolving Event - each time container resolves smth - it raises an event you can subscribe in other places of your project.

And many other practises... You can read more detailed here http://laravel.com/docs/5.1/container

like image 151
Silwerclaw Avatar answered Sep 18 '22 07:09

Silwerclaw