How to use PHP constant in routing YAML

2.1k Views Asked by At

I'm using Symfony 3.4

I managed to get the PHP constant to work for a service (as described in the documentation). But I can't figure out how to get it to work in a routing file. Here's what I have so far.

Entity:

namespace CompanyName\AppBundle\Entity\SomeDirectory;

class MyEntity
{
    public const STATUS__CREATED = 1;
}

routing.yml:

view_my_entity_with_status_created:
  path:       /created/
  defaults:
    _controller: "AppBundle:SomeOtherDirectory/Something:index"
    status: !php/const CompanyName\AppBundle\Entity\SomeDirectory\MyEntity::STATUS__CREATED

SomethingController:

public function indexAction(?int $status = null): Response
{
 // ...
}

From what I can tell the !php/const is being ignored since status is always null.

2

There are 2 best solutions below

0
yivi On BEST ANSWER

You can't in Symfony 3.4.

Using !php/const in routing YAML configuration files was not enabled until Symfony 4.1.

While the feature was added to YamlFileLoader in 3.2, it was only enabled by default for the dependency injection component, not for the routing component.

This is when the feature was merged.

1
Florent Cardot On

Depending on your symfony version, this can be done with specific typo:

https://symfony.com/blog/new-in-symfony-3-2-php-constants-in-yaml-files

Before 3.2 it is not possible from 3.2 to 3.4

arguments:
            - '@app.other_service'
            - !php/const:AppBundle\Entity\BlogPost::MUM_ITEMS
            - !php/const:Symfony\Component\HttpKernel\Kernel::VERSION

after 3.4:

arguments:
            - '@app.other_service'
            - !php/const AppBundle\Entity\BlogPost::MUM_ITEMS
            - !php/const Symfony\Component\HttpKernel\Kernel::VERSION

for your routing file:

# config/routes.yaml
blog_list:
    path:       /blog/{page}
    controller: AppBundle:SomeOtherDirectory/Something:index
    defaults:
        status: !php/const CompanyName\AppBundle\Entity\SomeDirectory\MyEntity::STATUS__CREATED