Symfony Services: Is there a way to set a public property in `services.yml`?

639 Views Asked by At

Is there a way to set a public variable by means of the service definition in services.yml?

The reason is, that i am using the phpbrowscap library. To use a local file for resolving the browser i need use this line of code:

$this->browscap->localFile = "..."

unfortunately this poor property is public and does not have a setter. it's neither available in constructor.

so how would i set this property in services.yml? is that even possible to achieve?

this is the part in my services.yml:

browscap:
        class: Browscap
        arguments:
            - %browscap_cache_dir%

if there was a setter i would add callthere... but well...

2

There are 2 best solutions below

2
On BEST ANSWER

Have you tried using the property injection method of the DI-Container?

https://symfony.com/doc/current/service_container/injection_types.html#property-injection

app.newsletter_manager:
     class: AppBundle\Mail\NewsletterManager
     properties:
         mailer: '@mailer'
0
On

You can use Factory to configure instance of service:

services:
    # ...

    browscap:
        factory:   'AppBundle\Service\BrowscapStaticFactory:createBrowscap'
        arguments: ['%browscap_cache_dir%']

Factory class:

class BrowscapStaticFactory
{
    public static function createBrowscap($cacheDir)
    {
        $browscap = new Browscap();
        $browscap->localFile = $cacheDir;

        // ...

        return $browscap;
    }
}