Dru
Dru

Reputation: 556

How to get action name in zend framework 2 constructor

How do I get the action name in __contructor function for zf2

Basically I want to check if user is logged in else redirect him to login page

I used the below code in zend framework 1, looking for similar in zf2

if (Zend_Auth::getInstance()->hasIdentity()) {
  // If the user is logged in, we don't want to show the login form;
  if (in_array($this->getRequest()->getActionName(), 'login')) {
     $this->_helper->redirector('index', 'index');
  }
} else {
  if (!in_array($this->getRequest()->getActionName(), 'login')) {
     $this->_helper->redirector('login', 'user');
  }
}

Upvotes: 1

Views: 1596

Answers (4)

Chirag Shah
Chirag Shah

Reputation: 1474

get action name by this $this->getEvent()->getRouteMatch()->getParam('action', '');

Upvotes: 1

Sam
Sam

Reputation: 16455

In addition to the already existing answers:

The __construct() is a pretty bad place for such things. This is mainly for the reason that inside a lot of classes within ZF2, the Constructor doesn't know about it's surroundings. A lot of Information is only passed into the classes after it's initial construction.

When it comes to ACL-Checks and stuff like this, then the Controllers are generally a really bad place to do things. This stuff should happen as early as possible and you'd make use of ZF2's EventManager to hook into a certain Event to place your ACL Checks inside.

With the help of the ServiceManager then you'd be able to get access to the requested controller and action as well as your ACL-Service and you could choose to either redirect the user or let him pass.

As pointed out by Remi, luckily there's a couple of Modules out there who help you with your job. ZfcUser is okay. ACL Wise you'll probably want to check out BjyAuthorize, too.

Upvotes: 2

Nandakumar
Nandakumar

Reputation: 1101

To get Current Controller Action:

  $matches      = $this->getEvent()->getRouteMatch();
  $action          = $matches->getParam('action','');

Upvotes: 3

Remi Thomas
Remi Thomas

Reputation: 1528

Please use ZfcUser module and after installation it's pretty simple to integrate that

How to check if user is connected

https://github.com/ZF-Commons/ZfcUser/wiki/How-to-check-if-the-user-is-logged-in

Redirect

in controller.php

return $this->redirect()->toRoute('yourroute', array());

Other useful link

https://github.com/ZF-Commons/ZfcUser/wiki http://framework.zend.com/manual/2.2/en/modules/zend.mvc.plugins.html

Upvotes: 2

Related Questions