是应用程序(FQCN);足以在 Laravel 中创建服务吗?

问题描述 投票:0回答:1

我是 Laravel 新手,主要使用 Symfony。

最近,我看到一段代码,看起来像这样:

<?php 

namespace MyApp\SomeNamespace;

use MyApp\UserInteraction\Filter;

class MyClass {

    public function myMethod(){

        $filter = app(Filter::class);

        ...

我认为这会执行类似创建或检索单例之类的操作。假设这是 Laravel 中的标准做法,而不是我正在查看的应用程序特有的内容,那么注册服务是否需要任何其他步骤?

(在 Symfony 中,我们通常会有一个属性、几行 XML 或一些 YAML 来定义服务属性。我尝试查看

helpers.php
文件以了解发生了什么,虽然这给了我一些想法
app()
函数可能在做什么,它没有告诉我在 Laravel 中将类注册为服务是否需要额外的步骤。)

当我查看其他几个问题和教程以了解他们所说的内容时,它们都引用了此应用程序中不存在的

app.config
文件。所以我认为情况在 Laravel 的更高版本中发生了变化。

laravel singleton laravel-8 soa
1个回答
0
投票

如果我没记错的话,Laravel 将自动解析您想要注入的服务:

class ExampleController
{
    // The ExampleService will be automatically resolve
    public function __construct(ExampleService $service) {}
}

app()
帮助器返回 Laravel 容器的实例,但如果您在其中添加
FQCN
作为参数,它将解析该类:

app(); // it will return a instance of container

app()->make(Filter::class); // it will resolve the Filter::class

app(Filter::class); // ^ the same as the above

如果您想将服务类绑定到接口,请说:

interface House {}
class AncientHouse implements House {}
class HouseBuiler
{
    public function __construct(House $house) {}
}

如果您想使用

House
接口而不是确切的
AncientHouse
类,您需要将其绑定到
ServiceProvider
,以便容器可以猜测您要注入的是
AncientHouse
类。

register()
内的
AppServiceProvider

方法中
public function register()
{
    $this->app->bind(House::class, AncientHouse::class);
}

我的英语不好,所以我希望我能正确解释。

参考资料:

服务容器

服务提供商

© www.soinside.com 2019 - 2024. All rights reserved.