我目前正在与CakePHP3.x一起在一个大项目中工作,我正在尝试使代码尽可能简洁。您可以在第一张图片上看到数据库的视觉结构:
一个用户有多个角色。使用Auth组件和前缀系统,我成功地保护了大多数页面,而没有太多麻烦。但是,在网站的某些部分,问题更加复杂。
以下是特殊用户可以做的事的快速示例:
Local Manager (secured by the prefix /local)
-- Can edit only his own local group
Regional Manager (secured by the prefix /region)
-- Can edit every local groups included in his region (with /local)
-- Can edit his own region (with /region)
National Manager (secured by the prefix /national)
-- Can edit every region in his own zone (with /region)
存在遗留系统,例如:本地<地区<国家。
在URL“ local / edit /:id”上,我不得不做类似的事,而这并不是我真正值得骄傲的事。
<?php
# No id provided : so this is the creation of a new local group
if($id == null){
# If the user is not a region or a national manager, throw an error
if(!array_key_exists('region', $this->viewVars['authUser']['auth'])
&& !array_key_exists('national', $this->viewVars['authUser']['auth'])
&& !array_key_exists('dev', $this->viewVars['authUser']['auth'])) {
throw new NotFoundException(__("Impossible de créer un groupe local (1)"));
}
# This is an update
} else {
# Check the local group with the region informations
$regionID = $this->LocalGroups->find('all')
->select(['region_id'])
->where(['LocalGroups.id'=>$id])
->first();
# Check the id of the user through the local group table (only has one relationship)
$userRegionID = $this->LocalGroups->find('all')
->select(['LocalGroups.region_id'])
->where(['id'=>$this->Auth->user()['local_group_id']])
->first();
# The region dosn't exist, throw an error
if(!$regionID){
throw new NotFoundException(__('Impossible de modifier ce groupe local (2)'));
}
# The user is a region manager nor a national manager
if(array_key_exists('region', $this->viewVars['authUser']['auth'])
&& !array_key_exists('dev', $this->viewVars['authUser']['auth'])
&& !array_key_exists('national', $this->viewVars['authUser']['auth'])){
# If the id of the region associated to the local group is different than the id of the region associated to the user, throw an error
if($regionID->region->id != $userRegionID->region_id){
throw new NotFoundException(__('Impossible de modifier ce groupe local (3)'));
}
}
# If the user is a local manager he can only edit his own local group
elseif(array_key_exists('local', $this->viewVars['authUser']['auth'])
&& !array_key_exists('dev', $this->viewVars['authUser']['auth'])
&& !array_key_exists('region', $this->viewVars['authUser']['auth'])
&& !array_key_exists('national', $this->viewVars['authUser']['auth'])){
# Check if he owns the local group
if($id != $this->viewVars['authUser']['local_group_id']){
throw new NotFoundException(__('Impossible de modifier ce groupe local (4)'));
}
}
}
那是一个很长的代码,我总是非常担心我错过某些东西或条件,或者某些东西。另外,我必须在其他页面上再次使用此代码。因此,我尝试使用它创建一个组件,但是几乎不可能对其中的数据库进行正确的访问,因此我不得不对其进行复制,而且我真的不喜欢这样做。
我真的需要找到一个很好的计划来构造我的代码。你能帮我吗?
加油, xSPx