Answer the question
In order to leave comments, you need to log in
How to organize controller(s) in YII2 for an authorized user and a guest on the same URL?
I want a landing page with authorization and links to registration, password reset, etc. to open for the guest on the main page of the site, and after authorization, he also remains at the url of the main page, but already in his account, which has nothing to do with the guest landing. Some pages may also have the same URL for the guest and user.
What is the best way to organize this?
The option in the action is to check whether the user is authorized or not, and depending on this, I don’t like to display the corresponding view.
I would like to separate the controllers - for an authorized user, their own controller with their own actions, for a guest, their own.
How do you solve such a problem?
Framework Yii2.
Answer the question
In order to leave comments, you need to log in
In principle, you know whether a user is authorized or not even before the routing stage, so you can set different routing rules for authorized users and not authorized. Somehow like that.
class ConditionalRouting implements BootstrapInterface
{
/**
* @var array
*/
public $guestRules = [
'' => 'guest/index',
];
/**
* @var array
*/
public $userRules = [
'' => 'user/index'
];
/**
* @inheritDoc
*/
public function bootstrap($app)
{
$manager = \Yii::$app->urlManager;
$manager->addRules(\Yii::$app->user->isGuest ? $this->guestRules : $this->userRules, false);
}
}
...
'bootstrap' => [
\app\components\ConditionalRouting::class
],
...
The option in the action is to check whether the user is authorized or not, and depending on this, I don’t like to display the corresponding view.
why vyuhu. different action for different users. you can make it a module, and in the module check the desired user and give the necessary module controller
"I don't like the option in the action to check whether the user is authorized or not, and depending on this, I don't like to display the corresponding view." and in vain, this is the most obvious and not a bad option. Naturally, it is better to move the contents of the check blocks into separate methods for greater readability.
As an alternative to what was suggested above, there is such an idea. But here the problem will be somewhat redefined.
public function __construct($id, $module)
{
parent::__construct($id, $module);
if (Yii::$app->user->isGuest) {
return $this->redirect('/login/', 302);
} else {
return false;
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question