考虑一个由WordPress制作的具有多个角色和功能的复杂系统。以一个大学网站为例。
大学网站可以将新闻发布到家中,还可以管理特定课程的内容,等等。
在复杂场景中保持角色和能力有序的最佳做法是什么?
考虑一个由WordPress制作的具有多个角色和功能的复杂系统。以一个大学网站为例。
大学网站可以将新闻发布到家中,还可以管理特定课程的内容,等等。
在复杂场景中保持角色和能力有序的最佳做法是什么?
回答我自己的问题,如果您的系统不是性能关键型的,您可以使用插件,例如User Role Editor:
它支持多站点、每个用户多个角色等。目前这种结构的主要优点是为角色提供一个专用文件夹,使其保持有序,并提供一个基本的OOP结构。这可以通过一些方法来扩展,例如,帮助分配自定义帖子类型功能等。
plugins/custom-roles-manager/custom-roles-manager.php
<?php
/*
* Plugin Name: Custom Roles Manager
* Description: This plugin handles roles capabilities.
* Requires PHP: 5.3
*/
defined(\'ABSPATH\') OR exit;
/** Runs only when the plugin is activated */
register_activation_hook(__FILE__, \'custom_roles_manager_activate\');
function custom_roles_manager_activate()
{
require_once(__DIR__ . \'/RoleInterface.php\');
// This is the folder we add roles on
$roles_folder = __DIR__ . \'/roles\';
// If it throws anything, WordPress will automatically disable the plugin and show the notice
$roles = crm_get_roles_in_folder($roles_folder);
// Give developer a chance to filter the roles for any reason
$roles = apply_filters(\'crm_get_roles\', $roles);
foreach ($roles as $role) {
// Filter might add $role that does not implement RoleInterface
if ($role instanceof RoleInterface) {
$role->add();
} else {
throw new Exception(\'All roles handled by Custom Roles Manager must implement RoleInterface interface.\');
}
}
}
/**
* Returns an array of concrete classes that implements RoleInterface
* in a given directory
*
* @param $dir
*
* @return array
* @throws ReflectionException
*/
function crm_get_roles_in_folder($dir)
{
$roles = array();
$roles_files = new RegexIterator(
new DirectoryIterator($dir),
\'/\\.php$/\',
RegexIterator::MATCH
);
foreach ($roles_files as $role_file) {
include_once($role_file->getPathname());
$r = new ReflectionClass($role_file->getBasename(\'.php\'));
if ($r->implementsInterface(RoleInterface::class)) {
$roles[] = $r->newInstance();
}
}
return $roles;
}
plugins/custom-roles-manager/RoleInterface.php
<?php
interface RoleInterface
{
/**
* Function that has to be implemented for
* each concrete class to actually add the role.
*/
public function add();
}
plugins/custom-roles-manager/roles/PublicRelationsRole.php
<?php
class PublicRelationsRole implements RoleInterface
{
public function add()
{
add_role(
\'public_relations\',
__(\'Public Relations\'),
[
\'read\',
\'edit_post\',
\'publish_post\',
\'delete_post\',
]
);
}
}
示例场景:创建“其他角色”创建文件wp内容/插件/自定义角色管理器/角色/SomeOtherRole.phpRoleInterface 并创建add
方法,该方法调用add_role
来自WordPress的函数随着时间的推移,您的复杂角色系统将有一个专门的文件夹供他们使用,这有助于使用OOP使其保持有序,OOP提供了一些关于代码随时间重复使用的选项。
我创建了一个界面,允许用户执行一定数量的操作,每个操作都有相关的功能(包括访问该界面)。我想有一个基本的能力(这里是原始的?)如果用户想要执行所有其他操作,则需要具备:如果用户可以删除项目,则用户还必须能够访问该界面。有几个插件允许添加/删除功能:我想防止出现用户可以删除但无法访问界面的情况。我知道,由于帖子类型、元功能和map\\u meta\\u cap filter,我很难将其应用到我的插件中。我可以一直检查这两个选项,但权限层次结构最终会更加复杂(比如,3个级别-用户必须具有访问\\u界面、创建\