指尖上的记忆指尖上的记忆
首页
  • 基础
  • Laravel框架
  • Symfony框架
  • 基础
  • Gin框架
  • 基础
  • Spring框架
  • 命令
  • Nginx
  • Ai
  • Deploy
  • Docker
  • K8s
  • Micro
  • RabbitMQ
  • Mysql
  • PostgreSsql
  • Redis
  • MongoDb
  • Html
  • Js
  • 前端
  • 后端
  • Git
  • 知识扫盲
  • Golang
🌟 gitHub
首页
  • 基础
  • Laravel框架
  • Symfony框架
  • 基础
  • Gin框架
  • 基础
  • Spring框架
  • 命令
  • Nginx
  • Ai
  • Deploy
  • Docker
  • K8s
  • Micro
  • RabbitMQ
  • Mysql
  • PostgreSsql
  • Redis
  • MongoDb
  • Html
  • Js
  • 前端
  • 后端
  • Git
  • 知识扫盲
  • Golang
🌟 gitHub

今天在分析之前的项目的时候,发现有几处配置不太清楚,就翻了一下symfony的官方文档,总结如下:

全面讲解symfony的自动注入原理: https://symfony.com/doc/5.4/service_container/autowiring.html

# config/services.yaml
services:
    # ...

    # the id is not a class, so it won't be used for autowiring
    app.rot13.transformer:
        class: App\Util\Rot13Transformer
        # ...

    # but this fixes it!
    # the "app.rot13.transformer" service will be injected when
    # an App\Util\Rot13Transformer type-hint is detected
    App\Util\Rot13Transformer: '@app.rot13.transformer'
    
This creates a service "alias", whose id is App\Util\Rot13Transformer. Thanks to this, autowiring sees this and uses it whenever the Rot13Transformer class is type-hinted
(这创建了一个服务 "别名",其ID是App\Util\Rot13Transformer。多亏了这一点,自动布线看到了这一点,并在Rot13Transformer类被类型提示时使用它)
  
通过别名实现自动注入: https://symfony.com/doc/5.4/service_container/autowiring.html#using-aliases-to-enable-autowiring
   
通过setter方法注入: https://symfony.com/doc/5.4/service_container/autowiring.html#autowiring-other-methods-e-g-setters-and-public-typed-properties
  
控制器里自动注入: https://symfony.com/doc/5.4/controller.html#controller-accessing-services
  
你怎么知道要使用LoggerInterface的类型提示?你可以阅读你所使用的任何功能的文档,或者通过运行以下程序获得一个可自动连接的类型提示列表:  
php bin/console debug:autowiring
  
对于容器中所有可能的服务的完整列表,请运行:  
php bin/console debug:container
  
还有一种与服务有关的参数。在YAML配置中,任何以@开头的字符串都被认为是服务的ID,而不是普通字符串:
# config/services.yaml
services:
    App\Service\MessageGenerator:
        arguments:
            # this is not a string, but a reference to a service called 'logger'
            - '@logger'

            # if the value of a string argument starts with '@', you need to escape
            # it by adding another '@' so Symfony doesn't consider it a service
            # the following example would be parsed as the string '@securepassword'
            # - '@@securepassword'

其实内容还是比较多的,实际使用主要是在 config/service.yaml文件里配置各种服务。