我正在从亚历山大·罗曼年科视频中学习Zend,我对zend_acl
有问题,我已经在application.ini
中声明了数据库连接:
resources.db.params.dbname = zftutorial
resources.db.params.username = root
resources.db.params.password =
resources.db.params.hostname = localhost
我已经在我的模型中添加了 LibraryAcl.php:
<?php
class Model_LibraryAcl extends Zend_Acl
{
public function __construct()
{
$this -> add(new Zend_Acl_Resource('book'));
$this ->add(new Zend_Acl_Resource('add'),'book');
$this ->add(new Zend_Acl_Resource('edit'),'book');
$this->add(new Zend_Acl_Resource('books'));
$this->add(new Zend_Acl_Resource('list'),'books');
$this->addRole(new Zend_Acl_Role('user'));
$this->addRole(new Zend_Acl_Role('admin'),'user');
$this ->allow('user','books','list');
$this->allow('admin','book','edit');
$this->allow('admin','book','add');
}
}
并更改了引导程序.php :
protected function _initAutoload()
{
$moduleLoader = new Zend_Application_Module_Autoloader(array( 'namespace' => '',
'basePath' => APPLICATION_PATH));
$acl = new Model_LibraryAcl;
$auth = Zend_Auth::getInstance();
$fc = Zend_Controller_Front::getInstance();
$fc->registerPlugin(new Plugin_AccessCheck($acl, $auth));
return $moduleLoader;
}
我还在插件中添加了访问检查.php:
<?php
class Plugin_AccessCheck extends Zend_Controller_Plugin_Abstract
{
private $_acl = null;
private $_auth = null;
public function __construct(Zend_Acl $acl, Zend_Auth $auth){
$this ->_acl = $acl;
$this->_auth = $auth;
}
public function preDispatch(Zend_Controller_Request_Abstract $request)
{
$resource = $request->getControllerName();
$action = $request->getActionName();
$identify = $this->_auth->getStorage()->read();
$role = $identify->role;
if (!$this->_acl->isAllowed($role , $resource, $action)){
$request->setControllerName('authentication')
->setActionName('login');
}
}
}
最后,这是我在本地主机中的数据库-ZF教程:
Database: `zftutorial`<br>
Table structure for table `books`<br>
CREATE TABLE IF NOT EXISTS `books` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(100) NOT NULL,
`author` varchar(500) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;
INSERT INTO `books` (`id`, `title`, `author`) VALUES
(1, 'onvane ketab', 'author ketab avali'),
(2, 'onvane ketab dovomi', 'author ketab dovomi'),
(3, 'onvan3', 'author varc3'),
(4, 'onvan4', 'author varc4');<Br>
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(100) NOT NULL,
`password` varchar(100) NOT NULL,
`role` varchar(10) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `username` (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;<br>
INSERT INTO `users` (`id`, `username`, `password`, `role`) VALUES
(1, 'john', 'pass1', 'user'),
(2, 'george', 'pass2', 'admin');
发生此错误:
Notice: Trying to get property of non-object in C:wampwwwZendworkspacestestapplicationpluginsAccessCheck.php on line 17
我认为
这是因为尚未进行身份验证。
试试这个:
if ($this->_auth->hasIdentity()) {
$identify = $this->_auth->getStorage()->read();
$role = $identify->role;
}