<?php
// Create ACL object
$acl = new Zend_Acl();
// Define roles
$acl->addRole(new Zend_Acl_Role('guest')); // Define guest role
$acl->addRole(new Zend_Acl_Role('user')); // Define user role
// Define resources
$acl->addResource(new Zend_Acl_Resource('index')); // Define the index resource
$acl->addResource(new Zend_Acl_Resource('profile')); // Define the profile resource
// Assign permissions to roles
$acl->allow('guest', 'index'); // Guests can access the index page
$acl->allow('user', 'index'); // Users can access the index page
$acl->allow('user', 'profile'); // Users can access the profile page
?>
<?php
class IndexController extends Zend_Controller_Action
{
public function init()
{
parent::init();
// Get the role of the currently logged-in user
$role = Zend_Auth::getInstance()->getIdentity()->role;
// Check if the user is allowed to access the current resource
if (!$acl->isAllowed($role, 'index', 'index')) {
$this->_redirect('/error/not-allowed'); // If not allowed, redirect to an error page
}
}
public function indexAction()
{
// Render the index view
}
}
?>
In the code above, the init method of the controller retrieves the role of the currently logged-in user and uses the isAllowed method of the ACL object to check if the user has permission to access the specified resource. If the user does not have permission, they are redirected to an error page.
Whether you are developing a permission management system or protecting sensitive pages, the ACL component in Zend Framework provides strong support to help ensure the security and reliability of your web application.