سؤال

Imagine this scenario:

  • There are users and groups. There is also a Membership entity to map the ManyToMany relation
  • Users can create, join, leave, and send comments to the groups they are members of.

There are several "main" templates in the application:

  • Last updated groups
  • Groups a signed in user is member of
  • Other group list page, like a search result

There is also a "minigroup" template, which shows info like #members, #comments, a mark if the current signed in user is member, has comments in, or has created the group

The main templates are constructed looping and including the minigroup template.

The minigroup template needs to know if a user is member, if has comments, etc...

How would you manage this logic?

  • Get all the data in the controller for each action that involves a list of groups
  • An entity method that returns an array of ids for which the user is member, or has comments, etc.
  • Store this array in the session when login is made and update it when a user comments, joins, leaves...

How would you make the minigroup template aware of the cases.

  • Each minigroup could receive some booleans "isMember" "hasComments" from the include statement
  • Each minigroup could receive a list of groups for which the user is member, a list of comments, etc. And then check if current group id is in that list

Right now I have the entity methods and boolean flags implemented, but I'm not sure if there is a more idiomatic or efficient way of doing it.

{% set userGroups = app.user ? app.user.participatedGroupIds : {} %}
{% set userComments = app.user ? app.user.commentedGroupIds : {} %}
{% for group in groups %}
  {% set vars = {'isMember':group.id in userGroups, 'hasComments':group.id in userComments} %}
  {% include 'GroupBundle:Default:minigroup.html.twig' with vars %}
{% endfor %}

How would you manage this scenario?

Do you know a better way of soing it?

Thanks!

هل كانت مفيدة؟

المحلول

For my part, your example puts too much business logic into the view. "Is a user in this group" is valid as a templating question, but not valid for the template itself to solve.

So, for my part, I'd put a query method on your User entity, and leverage that in the view.

/* ... User Entity Class ... */

/**
 * Does the User participate in the provided Group?
 *
 * @param Group $group The Group entity to check for participation
 * @return boolean
 */  
public function participatesInGroup( Group $group )
{
  return in_array( $group->getId(), $this->participatedGroupIds() );
}

Then in your template you could either do

{% for group in groups %}
  {% set vars = {'isMember': app.user.participatesInGroup(group)} %}
  {% include 'GroupBundle:Default:minigroup.html.twig' with vars %}
{% endfor %}

Or skip the set line altogether and let the template logic in minigroup.html.twig make the query on its own.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top