Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
229 views
in Technique[技术] by (71.8m points)

php - How to access an application parameters from a service?

From my controllers, I access the application parameters (those in /app/config) with

$this->container->getParameter('my_param')

But I don't know how to access it from a service (I imagine my service class is not supposed to extend SymfonyBundleFrameworkBundleControllerController).

Should I map needed parameters into my service registration like this:

#src/Me/MyBundle/Service/my_service/service.yml
parameters:
    my_param1: %my_param1%
    my_param2: %my_param2%
    my_param3: %my_param3%

or something similar? How should I access to my application parameters from a service?


This question seems like the same but mine actually answers to it (parameters from a controller), I'm talking about accessing from a service.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can pass parameters to your service in the same way as you inject other services, by specifying them in your service definition. For example, in YAML:

services:
    my_service:
        class:  MyBundleServiceMyService
        arguments: [%my_param1%, %my_param2%]

where the %my_param1% etc corresponds to a parameter named my_param1. Then your service class constructor could then be:

public function __construct($myParam1, $myParam2)
{
    // ...
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...