Skip to content

Concatenate strings in config #203

@mnapoli

Description

@mnapoli

In config files we often need to concatenate strings, but by referencing other container entries (i.e. lazy concatenation).

For example:

return [
    'path.application' => realpath(__DIR__ . '/..'),
    'path.tmp' => DI\link('path.application') . '/tmp',
    'log.file' => DI\link('path.tmp') . '/app.log',
];

Of course this example doesn't work because DI\link(...) is not a string (it's a reference to a container entry). The only solution for now would be to use a closure which is overly verbose:

return [
    'path.application' => realpath(__DIR__ . '/..'),
    'path.tmp' => DI\factory(function (ContainerInterface $c) {
        return $c->get('path.application') . '/tmp';
    }),
    'log.file' => DI\factory(function (ContainerInterface $c) {
        return $c->get('path.tmp') . '/app.log';
    }),
];

Solutions

String concatenation definition

We could add a new string definition which would concatenate all parameters (lazily):

return [
    'path.application' => realpath(__DIR__ . '/..'),
    'path.tmp' => DI\string(DI\link('path.application'), '/tmp'),
    'log.file' => DI\string(DI\link('path.tmp'), '/app.log'),
];

While it does look verbose, a PHP 5.6 example looks better:

return [
    'path.application' => realpath(__DIR__ . '/..'),
    'path.tmp' => string(link('path.application'), '/tmp'),
    'log.file' => string(link('path.tmp'), '/app.log'),
];

String expression definition

We could have a string definition which allows to construct strings with expressions:

return [
    'path.application' => realpath(__DIR__ . '/..'),
    'path.tmp' => DI\string('{path.application}/tmp'),
    'log.file' => DI\string('{path.tmp}/app.log'),
];

Mix

We could also make DI\string() provide both behaviors. I don't like having a choice though, because it can be confusing, but maybe this can be an exception?

Other containers

  • Symfony:
log.file: "%path.tmp%/app.log"
  • Laravel: no support (except closures)
  • Aura: no support (except closures)
  • ZF2: no mention of string parameters in the Service Manager, maybe handled by another component?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions