Skip to content

Instantly share code, notes, and snippets.

@artoodetoo
Last active August 29, 2015 13:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save artoodetoo/2f6253db03ad2d71856f to your computer and use it in GitHub Desktop.
Save artoodetoo/2f6253db03ad2d71856f to your computer and use it in GitHub Desktop.
It is my Symfony solution to track referral (partner) codes.
<?php
namespace Application\Me\MyUserBundle\EventListener;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Application\Me\MyUserBundle\Entity\User;
/**
* This service helps to save partner referral code for new registered user
* It should be registered as:
*
* @author artoodetoo
*/
class ReferralListener
{
/**
* @var ContainerInterface
*/
protected $container;
/**
* Instantiate listener. Inject container to access services
*
* @param ContainerInterface $container
*/
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
/**
* Intercept all HTTP requests, and keep track referral
*
* @param GetResponseEvent $event
*/
public function onKernelRequest(GetResponseEvent $event)
{
$request = $event->getRequest();
if ($request->query->has('_ref')) {
// It should be done for guests only
$securityContext = $this->container->get('security.context');
$isLoggedIn = ($securityContext->getToken() &&
($securityContext->isGranted('IS_AUTHENTICATED_FULLY') ||
$securityContext->isGranted('IS_AUTHENTICATED_REMEMBERED')));
if (!$isLoggedIn) {
$code = $request->query->get('_ref');
$session = $this->container->get('session');
$session->set('_ref', $code);
}
}
}
/**
* Intercept all ORM prePersist events, and store referral if applicable
*
* @param LifecycleEventArgs $args
*/
public function prePersist(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
if ($entity instanceof User) {
$session = $this->container->get('session');
if ($session->has('_ref')) {
$entity->setFollowRef($session->get('_ref'));
}
}
}
}
services:
# Create Request & ORM Listener
sandbox_init_cms.request_listener:
class: Application\Me\MyUserBundle\EventListener\ReferralListener
arguments: [ @service_container ]
tags:
- { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }
- { name: doctrine.event_listener, event: prePersist }
<?php
namespace Application\Me\MyUserBundle\Entity;
use Another\FOSUserDescendant\Entity\BaseUser;
class User extends BaseUser
{
/**
* @var string $ref This User's reference code
*/
protected $ref;
/**
* @var string $followRef Who do this user follow?
*/
protected $followRef;
public function __construct()
{
parent::__construct();
$this->ref = md5(uniqid());
}
// more fields plus setters/getters ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment