我创建了 Phalcon PHP 应用程序, 我有 3 个不同的用户配置文件:(ID: 1) 管理员、(ID: 2) 会计师和 (ID: 3) 仓库。
例如,我希望我的应用程序能够根据这些配置文件呈现 View
controllerName/index.1.volt //for Administrators
controllerName/index.2.volt //for Accountants
controllerName/index.3.volt //for Warehouses
但是当找不到这些文件时,我的应用程序将回退到:
controllerName/index.volt
我该如何实现这一目标?
最佳答案
一种方法,虽然很困惑,但会使用 controlerName/index.volt
作为“登陆页面”,然后从那里检查 if 语句来决定用户的角色是什么。然后从 if 语句中使用像 {{partial("index.1.volt") }}
这样的部分,但您需要为每个 Controller 对其进行硬编码...哎呀.. .
不过,我推荐的一个好的解决方案是利用 View 的 exists方法来检查 Controller 中是否存在 View 。这个想法是您将此方法传递给您正在查找的 View 文件的字符串路径,但省略扩展名。省略扩展名的原因是 Phalcon 允许您使用多个渲染引擎,因此混合使用 .volt
和 .phtml
的应用程序可以工作。
假设您使用的是这样的用户角色:
define('GUEST_ROLE',0);
define('ADMIN_ROLE',1);
define('ACCOUNTANT_ROLE',2);
define('WAREHOUSE_ROLE',3);
(访客角色的值为 0)我建议让所有 Controller 扩展 ControllerBase然后在你的ControllerBase中定义以下两个方法:
public function getUserLevel()
{
if($this->session->has('userLevel'))
{
$userLevel=$this->session->get('userLevel');
return (int)$userLevel;
}else{
return 0;//default to guest
}
}
protected function initialize()
{
$controllerName=$this->dispatcher->getControllerName();
$actionName=$this->dispatcher->getActionName();
$userLevel=$this->getUserLevel();
if($this->view->exists("$controllerName/$actionName.$userLevel"))
{
$this->view->pick("$controllerName/$actionName.$userLevel");
}
//No reason to add an else, Phalcon defaults to "$controllerName/$actionName"
}
只要确保,如果您需要为扩展 ControllerBase 的特定 Controller 定义自定义“初始化”方法,例如要向与 Controller 相关的所有页面添加标题前缀,请调用 parent::initialize();
否则它不会被调用。但这仅当您要覆盖该方法时才有效。
您可能已经在使用 ControllerBase 并执行类似的逻辑,如果是这样,您需要编辑现有的“初始化”方法并将我的代码与您的代码合并。
祝你编码愉快。
关于php - PHALCON PHP - 基于用户配置文件的不同 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33991104/