Roland Franssen
Contributed by Roland Franssen in #21027

Generating URLs in a command console is tricky because the console context doesn't know anything about HTTP requests, virtual hosts and domain names. This means that generating an absolute URL in a console command will always use http://localhost as the host name.

Symfony solves this problem with the router.request_context.* parameters, which define the hostname, HTTP scheme and base URL for console commands. When generating asset URLs with the asset() function in a command, the same problem occurs.

For example, if your application is installed in a subdirectory and have configured this parameter:

1
2
# app/config/parameters.yml
router.request_context.base_url: '/subfolder'

A call to asset('/foo/image.jpg') will result in /foo/image.jpg URL instead of the expected /subfolder/foo/image.jpg.

That's why in Symfony 3.4 we've introduced two new parameters called asset.request_context.base_path and asset.request_context.secure to define the default request context for assets. In this same application, if you define this new parameter:

1
2
# app/config/parameters.yml
asset.request_context.base_path: '/subfolder'

Now, the asset('/foo/image.jpg') function will generate the expected /subfolder/foo/image.jpg URL.

Published in #Living on the edge