简体   繁体   English

Laravel 中的依赖注入

[英]Dependency injection in Laravel

Coming for a JavaScript and Java background, I find dependency injection in Laravel (or PHP) extremely confusing.对于 JavaScript 和 Java 背景,我发现 Laravel(或 PHP)中的依赖注入非常令人困惑。

For example (Laravel 5.1), in Middleware/Authenticate the constructor takes a Guard object.例如(Laravel 5.1),在 Middleware/Authenticate 中,构造函数接受一个 Guard 对象。 I have search the codebase and the class Authenticate is never instantiated.我搜索了代码库,并且从未实例化过 Authenticate 类。

So where is the Guard coming from then?那么守卫从哪里来呢?

Thanks, SK.谢谢,SK。

Look at the laravel documentation:查看laravel文档:

Dependency injection is a fancy phrase that essentially means this: class dependencies are "injected" into the class via the constructor or, in some cases, "setter" methods.依赖注入是一个花哨的短语,本质上是这样的:通过构造函数或者在某些情况下通过“setter”方法将类依赖“注入”到类中。 http://laravel.com/docs/5.1/container http://laravel.com/docs/5.1/container

You can instantiate Guard in your code or fetch instance of Guard from somewere and pass it to Middleware/Authenticate constructor.您可以在代码中实例化 Guard 或从某个地方获取 Guard 实例并将其传递给 Middleware/Authenticate 构造函数。

EDITED : Guard is injected into the Middleware/Authenticate automatically somewere in laravel framework code at some point.编辑:Guard 被自动注入到中间件/身份验证中,某些时候在 laravel 框架代码中。 You better take a look on different example of Dependency injection in Laravel where all is visibly in your code.您最好查看 Laravel 中依赖注入的不同示例,其中所有内容都在您的代码中可见。

Defn : Dependency injection is a technique whereby one object supplies the dependencies of another object.定义:依赖注入是一种技术,其中一个对象提供另一个对象的依赖项。

You could visit the link below for a detailed explanation with ioc container explanation Visit : https://www.thelearninguy.com/dependency-injection-in-laravel-using-ioc-container您可以访问下面的链接以获取有关 ioc 容器解释的详细说明 访问: https : //www.thelearninguy.com/dependency-injection-in-laravel-using-ioc-container

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM