Laravel 5:app() 辅助函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33028544/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 12:28:31  来源:igfitidea点击:

Laravel 5: app() helper function

phphtmllaravel

提问by LoveAndHappiness

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.

在第二种情况下,我们加载 Flash 类并在我们的 flash 方法中实例化它。

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

我见过有人使用第一种方法,我想知道使用第二种方法是否有任何区别。

回答by Silwerclaw

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.

如果您像在示例中一样使用它 - 您将不会获得任何利润。但是 Laravel 容器在这种解析中提供了更多的功能,这是使用简单的实例化对象无法实现的。

  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 Countableinterface 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.
  1. 绑定接口- 您可以将特定接口及其实现绑定到容器中并将其解析为接口。这对于测试友好的代码和灵活性很有用 - 因为您可以轻松地在一个地方更改实现而无需更改接口。(例如,Countable在任何地方使用某个接口作为从容器解析的目标,而是接收它的实现。)
  2. 依赖注入- 如果您将绑定类/接口并将其作为某个方法/构造函数中的依赖项 - Laravel 将自动为您从容器中插入它。
  3. 条件绑定- 您可以绑定接口,但根据情况解决不同的实现。
  4. 单例- 您可以绑定对象的一些共享实例。
  5. 解析事件- 每次容器解析 smth 时 - 它会引发一个事件,您可以在项目的其他地方订阅。

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

以及许多其他实践......您可以在这里阅读更详细的内容http://laravel.com/docs/5.1/container