承接 althinect/enum-permission 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

althinect/enum-permission

Composer 安装命令:

composer require althinect/enum-permission

包简介

This package is to create permissions with enums

README 文档

README

Latest Version on Packagist Total Downloads

A Laravel package to easily manage Permissions with Enums and sync these permissions to your database. This package is built on top of Spatie's Laravel-Permission package, providing an enum-based approach to permission management. It's fully configured via the config file located at config/enum-permission.php.

Requirements

  • PHP 8.2 or higher
  • Laravel 10.0 to 13.x
  • Spatie/Laravel-Permission package

Installation

composer require althinect/enum-permission

This package automatically installs Spatie's Laravel-Permission package as a dependency, so you don't need to require it separately.

Publish configuration and migrations

Before running migrations, publish the configuration and migration files used by both Spatie's Laravel Permission package and this package:

php artisan vendor:publish --tag="permission-config"
php artisan vendor:publish --tag="enum-permission-config"

php artisan vendor:publish --tag="permission-migrations"
php artisan vendor:publish --tag="enum-permission-migrations"

Then run the migrations to set up Spatie's permission tables and this package's grouped-permission support:

php artisan migrate

If you are upgrading an existing installation, publishing enum-permission-migrations and running migrations will add the group column to your existing permissions table.

Configuration

The configuration file will be published to config/enum-permission.php. Customize your permissions, models path, and other options there.

Configuration Options

return [
    // Path to your models
    'models_path' => 'app/Models',
    
    // Your User model
    'user_model' => \App\Models\User::class,
    
    // Classes that models should extend for discovery
    'model_super_classes' => [
        'Illuminate\Database\Eloquent\Model',
        'Illuminate\Foundation\Auth\User',
    ],
    
    // Permission definitions for policy methods
    'permissions' => [
        [
            'method' => 'viewAny',
            'arguments' => ['{{userModelName}} $user'],
            'enum_case' => 'VIEW_ANY',
            'enum_value' => '{{modelName}}.view-any'
        ],
        // ... other permissions
    ],
    
    // Auth guards to create permissions for
    'guards' => [
        'web',
        'api',
    ],
    
    // Whether to sync permission groups
    'sync_permission_group' => false,
];

Migrations

This package builds on the database tables created by Spatie Laravel-Permission and ships an additional publishable migration under the enum-permission-migrations tag to add a group column to the permissions table.

When you install this package and run migrations, two things happen:

  1. The Spatie migrations create the core permission tables:

    • permissions - Stores all permissions
    • roles - Stores all roles
    • model_has_permissions - Maps permissions to users or other models
    • model_has_roles - Maps roles to users or other models
    • role_has_permissions - Maps permissions to roles
  2. This package adds its own migration to enhance the permissions table:

    • Adds a group column to the permissions table
    • Creates an index on the group column for faster queries

The group column is used when sync_permission_group is enabled in the config, allowing permissions to be organized by model name for easier filtering, grouping, and display in admin UIs.

Generated permission enums already include the HasPermissionGroup trait. By default, that trait derives the group name from the enum class name by removing the Permission suffix, so UserPermission becomes User, PostPermission becomes Post, and so on.

Usage

Generating Permission Enums

The permission:make command generates permission enums (and policies if requested) for your models.

# Generate for a specific model
php artisan permission:make User

# Generate with policy
php artisan permission:make User --policy

# Skip confirmation prompts (useful for CI/CD)
php artisan permission:make User --force

# Interactive selection of models
php artisan permission:make

Syncing Permissions to Database

The permission:sync command scans for permission enums and syncs them to the database.

# Sync all permissions
php artisan permission:sync

# Clean existing permissions before sync
php artisan permission:sync --clean

# Skip confirmation prompts (useful for CI/CD)
php artisan permission:sync --force

# Specify a custom path to scan for permissions
php artisan permission:sync --path=app/Domain/Auth/Permissions

Using Generated Permissions

// In your controllers or services
if ($user->hasPermissionTo(PostPermission::CREATE)) {
    // User can create posts
}

// In your policies
public function view(User $user, Post $post): bool
{
    return $user->hasPermissionTo(PostPermission::VIEW);
}

Directory Structure

After generation, your files will be organized as follows:

app/
├── Models/
│   └── User.php
├── Permissions/  (mirrors your Models directory structure)
│   └── UserPermission.php
└── Policies/
    └── UserPolicy.php

If your models use domain-driven structure, permission enums will follow the same structure:

app/
├── Domain/
│   └── Blog/
│       ├── Models/
│       │   └── Post.php
│       └── Permissions/
│           └── PostPermission.php
└── Policies/
    └── PostPolicy.php

Available Commands

  • permission:make {modelName?} {--P|policy} {--force} - Generate permission enums and optional policies
  • permission:sync {--C|clean} {--path=} {--force} - Sync permissions to database

Examples

Generated Permission Enum

namespace App\Permissions;

use Althinect\EnumPermission\Concerns\HasPermissionGroup;

enum UserPermission: string
{
    use HasPermissionGroup;

    case VIEW_ANY = 'User.view-any';
    case VIEW = 'User.view';
    case CREATE = 'User.create';
    case UPDATE = 'User.update';
    case DELETE = 'User.delete';
    case RESTORE = 'User.restore';
    case FORCE_DELETE = 'User.force-delete';
}

Generated Policy

namespace App\Policies;

use App\Models\User;
use App\Permissions\UserPermission;

class UserPolicy
{
    public function viewAny(User $user): bool
    {
        return $user->hasPermissionTo(UserPermission::VIEW_ANY);
    }
    
    public function view(User $user, User $model): bool
    {
        return $user->hasPermissionTo(UserPermission::VIEW);
    }
    
    // Additional methods for create, update, delete, etc.
}

Permission Groups

When sync_permission_group is enabled in the config, permissions will be grouped by model name and stored in the group column added by the published enum-permission-migrations migration. Generated enums already use HasPermissionGroup, which makes grouping work out of the box:

// In UserPermission.php
public static function getPermissionGroup(): string
{
    return str_replace('Permission', '', class_basename(static::class)); // Returns "User"
}

This feature uses the group column added to the permissions table by this package's migration. During permission:sync, the package calls getPermissionGroup() and stores the returned value in that column:

// Example of how permissions are stored with groups
[
    'name' => 'User.view',
    'guard_name' => 'web',
    'group' => 'User' // <-- This groups all User permissions together
]

This grouping makes it easy to:

  • Create model-based permission management UIs
  • Filter permissions by model in your admin panels
  • Apply batch operations to all permissions of a specific model

Error Handling

The package includes comprehensive error handling:

  • Database compatibility across PostgreSQL, MySQL, and other supported systems
  • Graceful failure when encountering invalid classes
  • File operation safeguards
  • Exception reporting for debugging

Extending the Package

You can extend the package's functionality by:

  1. Customizing the permission stubs in the config file
  2. Adding custom permission groups
  3. Creating middleware that uses the permission enums
  4. Building custom UI components for managing permissions

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

This package is open-source software licensed under the MIT license.

althinect/enum-permission 适用场景与选型建议

althinect/enum-permission 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 1.32k 次下载、GitHub Stars 达 1, 最近一次更新时间为 2024 年 12 月 21 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「laravel」 「althinect」 「enum-permission」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 althinect/enum-permission 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 althinect/enum-permission 我们能提供哪些服务?
定制开发 / 二次开发

基于 althinect/enum-permission 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 1.32k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 1
  • 点击次数: 9
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 1
  • Watchers: 2
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2024-12-21