Where to add additional helper functions for the object

I have an entity, such as Game, with some properties, such as time, and it has a load of Eventobjects under it. Some information about the game is implicitly stored in the entity, for example. number of deaths (determined by the number of deaths).

If I want to display the number of deaths in a template (which has access to the game object), where can I put the logic?

I can come up with several options, but I'm not sure if this is the β€œright” thing.

  • Put the getDeaths () function in the repository.
    I get the impression that where it was supposed to go, but I don’t know how to access this template correctly.
  • Place the getDeaths () function in an object The Game
    easiest way to do this is because it is easily accessible from a template.
  • Create a function in the controller
    It does not seem flexible to ask the controller for this information.
+4
source share
2 answers

If you implicitly save the number of deaths in the Game object, just add a function getDeaths()to the entity. You should probably have it there, and not just keep a public variable that can be changed anyway.

The repository method will be needed if you need to directly request the number of deaths from the database, in which case you can simply pass this directly to the template.

, ,

return array('game' => $game);

:

{{ game.numDeaths }}

, :

return array('game' => $game, 'numDeaths' => $numDeaths);

:

{{ numDeaths }}

, .

+1

/ twig:

public function getFunctions()
{
    return [
        new \Twig_SimpleFunction('number_of_death', [$this, 'getNumberOfDeath'])
    ]
}

public function getNumberOfDeath(Entity $entity)
{
    // logic

    return $return;
}

:

{{ number_of_death(entity) }}
+1

Source: https://habr.com/ru/post/1569067/


All Articles