Jinu Joseph Daniel
Jinu Joseph Daniel

Reputation: 6291

Yii 2 use same controller method / action in multiple controllers

I have a method checking whether user is logged in in my UserController.I need the same method in all the other controllers.How can I do the same without copy pasting the code to all controllers.

The controller method looks like

public function is_logged_in() {
	     $session = Yii::$app->session; 
	     $cookies = Yii::$app->request->cookies;
	     //print_r($session);
	     $session->open();
	     $session_cookie_name = Yii::$app->params['cookie_name_session_var'];
	     $logged_in = false;
	     //echo "-memn-".$cook_name.' is halle - ';
	     //print_r($_SESSION);
	     if(($cook_name = $session->get($session_cookie_name))) {
	     	//echo " - <pre>";
	     	//print_r($cookies);
	     	//exit;
	     	$write_cookies =  Yii::$app->response->cookies;
	     	//echo "</pre>";
	     	//echo $cookies->getValue($cook_name).' placenta';
		     if($u_token = $cookies->getValue($cook_name)) {
		     	echo "b";
			 	 if($u_token) {
			 	  echo "c"; 
			 	 	$write_cookies->remove($cook_name);
			 	 	unset($write_cookies[$cook_name]);
			 	 	$session->destroy();
			 	 	$session->open();
			 	 	$cookie_name = sha1($u_token).time();
			 	 	$session[$session_cookie_name] = $cookie_name;
			 	 	$write_cookies->add(new \yii\web\Cookie([
	            		'name' => $session[$session_cookie_name],
	            		'value' => $u_token,
	            		'expire' => time() + 6000000
	            	])); // around one hour expiry time
	            	$session->close();

			 	 	
			 	 	
			 	 	 
			 	 	
			 	 	$logged_in = true;
				 	 //echo $u_token;
			 	 }    
		     }  
	     }  
	     
	     if(!$logged_in) {
		     $session->destroy();
	     }
	     return $logged_in;
    }

Upvotes: 2

Views: 1867

Answers (2)

Mihai P.
Mihai P.

Reputation: 9357

In addition to arogachev's answer your code actually should sit in a class that extends the User component class http://www.yiiframework.com/doc-2.0/yii-web-user.html , not even to mention that the user identity class already does everything your code does (only much, much better). It comes with isGuest function.

Upvotes: 0

arogachev
arogachev

Reputation: 33538

1) You can create own component and put this method here or place it in the model (depends on logic of that method). Component can be placed for example in components folder (by default it doesn't exist). Then just use this component in any controllers you want.

2) If this code needs to be executed before or after certain actions, you can use behaviors.

3) You can use inheritance and create your custom controller that extends from yii\web\Controller, declare this method here and extend all other controllers where are you going to use this logic from your custom one.

Upvotes: 4

Related Questions