2010年2月2日星期二

Re: [fw-mvc] View and action helpers

There is already a view helper called isAllowed.

But, if you want to use your custom logic, the proper way to get an instance of an Action Helper in a View Helper is to statically retrieve it from the Action Helper Broker. That would prevent duplicate instances of the helper being created:
$aclActionHelper = Zend_Controller_Action_HelperBroker::getStaticHelper('acl');
Konr Ness

On Mon, Feb 1, 2010 at 6:12 PM, Christer Edvartsen <cogo@starzinger.net> wrote:
I'm working on an application where users should be able to log in.

I have an action helper that does acl stuff so I can control access in my actions by doing something like:

pulic function secretAction() {
   if (!$this->_helper->acl->isAllowed('Admin')) {
       // ...
   }
}

The acl helper fetches info from the authenticated used (if any) from Zend_Auth and so forth.

Now, in my views I would also like an acl helper that I can use to for instance decide which links to show in the menu. Since I already have a perfectly valid action helper that does everything I need I was wondering if it was kosher to simply instantiate that helper in my view helper.

class My_View_Helper_Acl extends Zend_View_Helper_Abstract {
   protected $helper = null;

   public function acl() {
       if ($this->helper === null) {
           $this->helper = new My_Controller_Helper_Acl();
       }

       return $this;
   }

   public function isAllowed($resource) {
       return $this->helper->isAllowed($resource);
   }
}

And in my views I can do:

<?php if ($this->acl()->isAllowed('Admin')): ?>
display link to admin page
<?php endif; ?>

Is this the way to do it or is there some other solution I could use?


--
Christer Edvartsen
cogo@starzinger.net
http://cogo.wordpress.com/

没有评论: