jundayw/policy 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

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

jundayw/policy

Composer 安装命令:

composer require jundayw/policy

包简介

A flexible policy verification system for Laravel, supporting dynamic return of permission identifiers through model methods and providing easy integration with middleware.

README 文档

README

Policy

A flexible policy verification system for Laravel, supporting dynamic return of permission identifiers through model methods and providing easy integration with middleware.

中文 | English

GitHub Tag Total Downloads Packagist Version Packagist PHP Version Support Packagist License

Table of Contents
  1. Installation
  2. Usage
  3. Contributing
  4. Contributors
  5. License

Installation

You can install the package via Composer:

composer require jundayw/policy

[back to top]

Usage

Model Preparation

The model to be verified (e.g., App\Models\User) must implement the Jundayw\Policy\Contracts\Policeable interface and use the Jundayw\Policy\Concerns\HasPolicy trait. Also, implement the getPolicies(string $ability, array $arguments = []): array method to return an array of permission identifiers that the current user possesses.

namespace App\Models;

use Jundayw\Policy\Concerns\HasPolicy;
use Jundayw\Policy\Contracts\Policeable;

class User extends Authenticatable implements Policeable
{
    use HasPolicy;

    public function getPolicies(string $ability, array $arguments = []): array
    {
        // Here you can obtain the user's permission list from the database, cache, etc.
        return [
            'backend.module.create',
            'backend.module.edit',
            'backend.policy.list',
            'backend.policy.create',
            'backend.policy.update',
            'backend.policy.destroy',
            'backend.role.*',
            'backend.*.*',
        ];
    }
}

Using Built-in Middleware

The package provides a policy middleware that you can use directly in controllers or routes for permission verification.

In the controller constructor:

class UserController extends Controller
{
    public function __construct()
    {
        $this->middleware('policy');
    }
}

In route definitions:

Route::middleware('policy')->group(function () {
    Route::get('/users', [UserController::class, 'index']);
    Route::post('/users', [UserController::class, 'store']);
    // ...
});

When a user is unauthorized, the built-in middleware throws a Jundayw\Policy\Exceptions\PolicyException. You should handle this exception according to your application's needs (e.g., return a 403 page or JSON response).

Custom Middleware

If you need more control (e.g., custom rules for generating permission identifiers), you can create your own middleware:

use Jundayw\Policy\Policy;
use Jundayw\Policy\Exceptions\PolicyException;

class CustomPolicyMiddleware
{
    public function handle($request, $next)
    {
        // Generate a permission identifier based on the request, e.g., "admin.user.update"
        $policy = $this->determinePolicy($request);

        if ($request->user()->can($policy, [Policy::class])) {
            return $next($request);
        }

        // Custom unauthorized behavior
        throw new PolicyException('Unauthorized', 403);
    }

    protected function determinePolicy($request)
    {
        // Example: dynamically construct a permission string from the route or request
        return $request->route()->getName();
    }
}

Custom Permission Identifier

Create a custom rule class for generating permission identifiers:

use Illuminate\Http\Request;
use Jundayw\Policy\Contracts\CanPoliceable;

class CustomPoliceable implements CanPoliceable
{
    public function __invoke(Request $request): mixed
    {
        if (app()->runningInConsole()) {
            return null;
        }

        return $request->path();
    }
}

Register it in the container:

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Jundayw\Policy\Contracts\CanPoliceable;

class AppServiceProvider extends ServiceProvider
{
    public function boot(): void
    {
        $this->app->bind(CanPoliceable::class, function () {
            return new CustomPoliceable;
        });
    }
}

Debug Mode

You can enable or disable permission verification by publishing the configuration file, which is useful for temporarily bypassing permission checks in development or testing environments.

Publish the configuration file:

php artisan vendor:publish --tag=policy-config

The configuration file will be located at config/policy.php with the following content:

<?php

return [
    /*
    |--------------------------------------------------------------------------
    | Policy Verification Switch
    |--------------------------------------------------------------------------
    |
    | When set to false, all permission checks will return true, i.e., no verification.
    | This can be used to temporarily disable the policy system in local development or testing.
    |
    */
    'enabled' => env('POLICY_ENABLED', true),
];

You can control the verification status by adding the following to your .env file:

POLICY_ENABLED=false

Exception Handling

When permission verification fails, the system throws a Jundayw\Policy\Exceptions\PolicyException. It is recommended to handle this exception uniformly in App\Exceptions\Handler, for example, by returning a friendly error page or JSON response:

public function register()
{
    $this->renderable(function (PolicyException $e, $request) {
        if ($request->expectsJson()) {
            return response()->json(['message' => 'Unauthorized'], 403);
        }
        return response()->view('errors.403', [], 403);
    });
}

Contributing

Contributions are what make the open source community such an amazing place to learn, inspire, and create. Any contributions you make are greatly appreciated.

If you have a suggestion that would make this better, please fork the repo and create a pull request. You can also simply open an issue with the tag "enhancement". Don't forget to give the project a star! Thanks again!

  1. Fork the Project
  2. Create your Feature Branch (git checkout -b feature/AmazingFeature)
  3. Commit your Changes (git commit -m 'Add some AmazingFeature')
  4. Push to the Branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

[back to top]

Contributors

Thanks goes to these wonderful people:

contrib.rocks image

Contributions of any kind are welcome!

[back to top]

License

Distributed under the MIT License (MIT). Please see License File for more information.

[back to top]

jundayw/policy 适用场景与选型建议

jundayw/policy 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 11 次下载、GitHub Stars 达 0, 最近一次更新时间为 2026 年 03 月 19 日, 在 PHP 生态内属于活跃度较高的组件。

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

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

围绕 jundayw/policy 我们能提供哪些服务?
定制开发 / 二次开发

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

  • 总下载量: 11
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 28
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

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

其他信息

  • 授权协议: MIT
  • 更新时间: 2026-03-19