Answer the question
In order to leave comments, you need to log in
Yii2. How to implement a referral system?
Good afternoon.
I'm trying to implement a referral program on the site. Right now it only works when going to the main page.
I just check the required GET parameter:
//SiteController actionIndex
$ref_name = Yii::$app->request->get('ref');
//Если есть параметр ref, то записываю куки
//И потом просто заново перенаправляю на главную страницу
$this->redirect(Yii::app()->getHomeUrl());
//MainController
public function beforeAction($action)
{
$ref_name = Yii::$app->request->get('ref');
//Далее стандартные проверки на наличие такого рефа и запись куки
//Но теперь надо перенаправить на запрашиваемую страницу
//убрав при этом GET параметр "ref"
return parent::beforeAction($action);
}
site.com/article?ref=123
site.com/article
site.com/article/view?id=20&ref=123
site.com/article/view?id=20
Answer the question
In order to leave comments, you need to log in
And if you forget to inherit from this controller somewhere? It is possible for you to decide without inheritance from the main controller. Hang the handler on the whole application using before or after:
'as beforeAction' => function () {
//Тут ваши действия для анонимной функции
}
'as beforeAction' => [
'class' => app\modules\users\behaviors\LastVisitBehavior::class
],
/**
* Страница сохранения реферера (пригласившего)
*
* @param int $id
*
* @return Response|string
*/
public function actionReferral(int $id)
{
if (Yii::$app->user->isGuest) {
ReferralHelper::setReferrerId($id);
}
return $this->redirect('site/registration');
}
/**
* Страница регистрации
*
* @return Response|string
* @throws \yii\base\InvalidArgumentException
* @throws \yii\db\Exception
*/
public function actionRegistration()
{
if (!Yii::$app->user->isGuest) {
return $this->goHome();
}
$userForm = new UserForm();
if ($userForm->load(Yii::$app->request->post())) {
$referrerId = ReferralHelper::getReferrerId();
$referrer = $referrerId !== null ? $this->getUser((int)$referrerId) : null;
$userForm->setReferrer($referrer);
if ($userForm->save() && $userForm->login()) {
$message = 'Спасибо за регистрацию.';
if ($referrer !== null) {
$message .= ' Вас пригласил ' . $referrer;
}
Yii::$app->session->setFlash('success', $message);
ReferralHelper::removeReferrer();
return $this->goHome();
}
$this->addErrorForForm($userForm);
}
$userForm->password = '';
return $this->render('registration', [
'model' => $userForm,
]);
}
class ReferralHelper
{
const KEY_REFERRER_ID = 'referrer_id';
public static function setReferrerId(int $referrerId)
{
\Yii::$app->getSession()->set(self::KEY_REFERRER_ID, $referrerId);
}
public static function getReferrerId()
{
return \Yii::$app->getSession()->get(self::KEY_REFERRER_ID, null);
}
public static function removeReferrer()
{
return \Yii::$app->getSession()->remove(self::KEY_REFERRER_ID);
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question