回答我自己的问题,如果您的系统不是性能关键型的,您可以使用插件,例如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.php实现它RoleInterface
并创建add
方法,该方法调用add_role
来自WordPress的函数停用并激活插件随着时间的推移,您的复杂角色系统将有一个专门的文件夹供他们使用,这有助于使用OOP使其保持有序,OOP提供了一些关于代码随时间重复使用的选项。