Skip to content

MembershipService

The MembershipService provides the main API for membership-related logic: checking whether a contact is a member of a target contact, and loading memberships for a contact or for a target.

Service ID: crm_membership.service
Class: Drupal\crm_membership\Service\MembershipService

Getting the service

Inject the service in your code, or use the static helper:

$membership_service = \Drupal::service('crm_membership.service');

Inject via constructor (recommended):

public function __construct(
  protected readonly MembershipService $membershipService,
) {}

Then register your class in services.yml with autowire: true or explicitly inject crm_membership.service.

Methods

isMember

public function isMember(Contact $contact, Contact $target): bool

Checks whether $contact is considered a member of $target.

  1. Direct memberships: Queries published memberships with membership_status = active that reference both the contact and the target, then for each uses its Membership Term plugin isActiveFor() (including grace periods).
  2. Indirect memberships: Loads all published membership_status = active memberships for the target and checks whether the contact is active via period applicable contacts and the term plugin (e.g. household memberships).
  3. Event: If still not a member, dispatches MembershipEvents::IS_MEMBER; subscribers can call MembershipIsMemberEvent::markAsMember().

Returns true if any step determines the contact is a member.

Note: The initial query filters on the membership_status field (active only) and the status published flag, not a full scan of all memberships. A membership with membership_status = future or expired, or that is unpublished, is never considered, even if period dates suggest otherwise.

getMemberships

public function getMemberships(Contact $contact): array

Returns all published memberships with membership_status = active that have the given contact in their contacts field. Return value is an array of Membership entities (keyed by ID). On storage/plugin errors, logs and returns an empty array.

Does not re-check term plugin activity — it returns entities by membership_status field only.

getMembershipsForTarget

public function getMembershipsForTarget(Contact $target): array

Returns all published memberships with membership_status = active whose target_contact is the given contact. Return value is an array of Membership entities (keyed by ID). Used internally by isMember() for indirect membership checks and can be used by custom code to list memberships for an organization (or other target).

Dependencies

The service depends on:

  • Term plugins: Activity checks delegate to the membership’s term plugin (via Membership::isActiveFor()).
  • Event dispatcher: The IS_MEMBER event is dispatched so other modules can extend or override “is member” logic.

See Events for subscribing to IS_MEMBER and Programmatic examples for usage patterns.