Symfony2 global function in entity

484 views Asked by At

I have a global function sanitizeName:

function sanitizeName($s) {
    return preg_replace('/somethingCrazy/', 'notSoCrazy', $s);
}

I need to use it in entity (e.g. for RSS generation), in Twig's template and in controller.

If I write it as service or add as Twig function/filter I will not be able to access it in entity as it will be just wrong. Obviously I can copy it to entity, but it's also nasty solution. How do I do this properly?

2

There are 2 answers

0
Jovan Perovic On BEST ANSWER

You could write your own class with static method:

class StringUtils{
    public static function sanitizeName($s) {
        return preg_replace('/somethingCrazy/', 'notSoCrazy', $s);
    }
}

Then, if you'd like, add a Twig filter/function which invokes this static method. This way, you have have access to it :

  • from within Twig template, via filter/function
  • entity classes by invoking `StringUtils::sanitizeName($someFoo)

Hope this helps...

0
COil On

Injecting services into entities is bad practice. So static method can be OK. But if you have code that you will use in multiple entities you could have a BaseEntity with several useful functions. For example:

/**
 * Base class for all project entities.
 */
class BaseEntity
{
        public function sanitizeName()
        {
            return preg_replace('/somethingCrazy/', 'notSoCrazy', $this->getName());
        }       
}

/**
 * My product entity.
 */        
class Product extends BaseEntity
{
    ...
}

Here the sanitize function can be used in all entities having a name property.