flightphp / permissions
Flight应用程序管理权限的库
v0.1.0
2024-06-04 05:24 UTC
Requires
- php: >=7.4
Requires (Dev)
- flightphp/core: ^3.10
- phpunit/phpunit: ^9.0
- rregeer/phpunit-coverage-check: ^0.3.1
- squizlabs/php_codesniffer: ^3.8
- wruczek/php-file-cache: ^0.0.5
This package is auto-updated.
Last update: 2024-09-04 05:55:48 UTC
README
权限是任何应用程序的重要组成部分。即使在RESTful API中,您也需要检查API密钥是否有执行请求操作的权限。在某些情况下,在中间件中处理认证是有意义的,但在其他情况下,拥有一个标准的权限集会更有帮助。
此库遵循基于CRUD的权限系统。有关如何实现的示例,请参阅 基本示例。
基本示例
假设您在应用程序中有一个功能,用于检查用户是否已登录。您可以创建一个权限对象,如下所示
// index.php require 'vendor/autoload.php'; // some code // then you probably have something that tells you who the current role is of the person // likely you have something where you pull the current role // from a session variable which defines this // after someone logs in, otherwise they will have a 'guest' or 'public' role. $current_role = 'admin'; // setup permissions $permission = new \flight\Permission($current_role); $permission->defineRule('loggedIn', function($current_role) { return $current_role !== 'guest'; }); // You'll probably want to persist this object in Flight somewhere Flight::set('permission', $permission);
然后在某个控制器中,您可能会有如下代码。
<?php // some controller class SomeController { public function someAction() { $permission = Flight::get('permission'); if ($permission->has('loggedIn')) { // do something } else { // do something else } } }
您还可以使用此功能来跟踪用户是否具有在应用程序中执行某些操作的权限。例如,如果用户可以通过某种方式与您的软件进行交互,您可以检查他们是否具有执行特定操作的权限。
$current_role = 'admin'; // setup permissions $permission = new \flight\Permission($current_role); $permission->defineRule('post', function($current_role) { if($current_role === 'admin') { $permissions = ['create', 'read', 'update', 'delete']; } else if($current_role === 'editor') { $permissions = ['create', 'read', 'update']; } else if($current_role === 'author') { $permissions = ['create', 'read']; } else if($current_role === 'contributor') { $permissions = ['create']; } else { $permissions = []; } return $permissions; }); Flight::set('permission', $permission);
然后在某个控制器中...
class PostController { public function create() { $permission = Flight::get('permission'); if ($permission->can('post.create')) { // do something } else { // do something else } } }
看看这有多有趣?让我们安装它并开始使用吧!
安装
只需使用Composer安装
composer require flightphp/permissions
文档
请访问 文档页面 了解更多关于使用方法和这个库有多酷! :)
许可证
MIT