Symfony2 Use PHP Class Constant in YAML Config?

2019-01-23 03:26发布

问题:

I know this is probably not possible, but is there a clean way to use a PHP class constant within a YAML config/services/etc. file for Symfony2?

For example, if I have this:

namespace My\Bundle\DependencyInjection;

class MyClass
{
    const MY_CONST = 'cookies';
}

Is something like this possible (in a .yml file):

services:
    my_service:
        class: Some\Class
        arguments:
            - %My\Bundle\DependencyInjection\MyClass::MY_CONST%

That'd go a long way in helping maintain consistency between the two.

回答1:

In versions before Symfony 3.2, injecting PHP-constants only works with XML:

<parameter key="my_service.my_const" type="constant">My\Bundle\DependencyInjection\MyClass::MY_CONST</parameter>

If you want to keep yor yml files, you could just import the xml-file into your services.yml. Mixing config styles might be a bit ugly, but as far as I know this is the only way to do it.

If this doesn't work for you, my comment to your question applies.



回答2:

For Symfony >=2.4 you can use expression language

Example:

'@=constant("Symfony\\Bridge\\Monolog\\Logger::INFO")'


回答3:

As of Symfony 3.2, it's also possible to use PHP constants in YAML files using a special !php/const: syntax:

parameters:
    bar: !php/const:PHP_INT_MAX

See the Symfony blog post for more details.


Please note: In Symfony 4 the syntax was slightly changed. You have to use a space instead of a double colon, for example:

parameters:
    bar: !php/const PHP_INT_MAX

Otherwise, you will get a FileLoaderLoadException with the message "Notice: Uninitialized string offset".



回答4:

It should be possible to insert argument as plain 'text' in config and inside class __construct($constant1) then request constant through variable by constant($constant1) function.

But I am not sure about global constants here, because they may not be defined at time of using, but it shouldn't be a problem for class constants with whole namespace, because namespace locator is already defined at moment of calling the class.

Example config:

services:
    my_service:
        class: Some\Class
    arguments:
        - 'My\Bundle\DependencyInjection\MyClass::MY_CONST'

and example class method:

public function __construct($arg1)
{
    $myRequiredConstantValue = constant($arg1);
}


回答5:

This is possible, but only when using eval'd code, which is generally frowned upon.

Given a class constant Permission::ACCESS_NONE e.g. you could do something like this in the yaml file:

permission: ACCESS_NONE

and the following in the code where you parse the yaml:

eval("return \The\Complete\Namespace\To\Permission::".$context['permission'].";");

This is of course butt-ugly code but it does work.



回答6:

This should work

arguments:
 - <?php echo My\Bundle\DependencyInjection\MyClass::MY_CONST."\n" ?>


标签: php symfony yaml