A
A
Alexander Sergin2015-06-09 17:15:52
symfony
Alexander Sergin, 2015-06-09 17:15:52

How to correctly implement a calculated field for Entity (Symfony/Doctrine)?

Good afternoon. Mastering Symfony/Doctrine.
There is an entity User with a subdomain field :

class User
{
    // ...

    // тут значение домена третьего уровня
    private $subdomain;

    public function setSubdomain($subdomain)
    {
        $this->subdomain = $subdomain;
    }
    
    public function getSubdomain()
    {
        return $this->subdomain;
    }

    // ...
}

There is a config:
acme:
    full_domain_template: http://{subdomain}.example.com

I would like to have a getFullDomain() method on the entity User , which would form the value of the full domain based on the config and the subdomain field . I see the following solution: create a User through a factory that will inject a value from the config into it. But the solution does not seem to be very successful. Who solves this problem? Perhaps the getFullDomain() method has no place at all on Entity, then where?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Pavlov, 2015-06-09
@alex_sergin

There are several solutions.
1) using a dirty hack to get the container and extract the necessary services and parameters from it. If you need to decide very quickly, then you can do it that way, but then do not forget to clean up after yourself when there is time for refactoring.
2) make a factory to create an entity (as you said)
These two options can be found in this question .
3) Pass the template through the method parameter:

class User
{
    // ...

    public function getFullDomain($template)
    {
        return str_replace("{subdomain}", $this->subdomain, $template);
    }
}

But the code that uses this entity must itself receive the template in order to pass it to the getFullDomain() method.
4) Make an extension for Twig . The solution depends on the purpose of this method - if the fully qualified domain name is displayed only in the view, then this is a good solution. The above documentation page shows a way to build a user|fullDomain filter, but it's not more difficult to make a function - fullDomain (user), whatever you like.
5) Make a service that will build the fully qualified domain name. This is the most universal way, because in all other cases you can call this service and use its method to build a name.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question