国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home PHP Framework Swoole How to use the Hyperf framework for permission control

How to use the Hyperf framework for permission control

Oct 20, 2023 pm 01:46 PM
Permission control hyperf framework

How to use the Hyperf framework for permission control

How to use the Hyperf framework for permission control

Introduction:
When developing an application, it is often necessary to implement permission control functions and give users different roles different permissions. The Hyperf framework is a high-performance PHP microservices framework that provides many powerful features and extensions, including flexible permission control. In this article, we will explore how to use the Hyperf framework to implement permission control and provide specific code examples.

1. Create a permission table
First, we need to create a permission table to store various permission information. Database tables can be created through Hyperf's data migration function. Execute the following command in the terminal to generate the migration file:

php bin/hyperf.php gen:migration create_permissions_table

Then add the following content to the generated migration file:

<?php

use HyperfDatabaseSchemaSchema;
use HyperfDatabaseSchemaBlueprint;
use HyperfDatabaseMigrationsMigration;
use HyperfDbConnectionDb;

class CreatetPermissionsTable extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        $tableName = 'permissions';
        $exists = Db::table('information_schema.TABLES')
            ->where('TABLE_SCHEMA', config('databases.default.dbname'))
            ->where('TABLE_NAME', $tableName)
            ->first();

        if (!$exists) {
            Schema::create($tableName, function (Blueprint $table) {
                $table->bigIncrements('id');
                $table->string('name')->unique()->comment('權(quán)限名稱');
                $table->string('guard_name')->default('web')->comment('守衛(wèi)名稱');
                $table->timestamps();
            });
        }
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('permissions');
    }
}

Next, we need to add the following content to the main configuration file of the project Add the following content to config/autoload/permissions.php:

<?php

return [
    'default' => [
        'guard_name' => 'web',
        'permissions' => [
            // 在這里添加你的權(quán)限
            'create_post',
            'edit_post',
            'delete_post',
            // ...
        ],
    ],
];

Then run the following command on the command line to perform database migration:

php bin/hyperf.php migrate

2. Define the user role model
In the Hyperf framework, we need to define a user model, which is used to manage user roles and permissions. We can create a user model by inheriting the HyperfDatabaseModelModel class. Execute the following command in the terminal to generate the user model:

php bin/hyperf.php gen:model User

Then add the following code to the generated user model file:

namespace AppModel;

use HyperfDbConnectionModelModel;
use HyperfUtilsApplicationContext;

class User extends Model
{
    protected $guarded = [];

    public function roles()
    {
        return $this->belongsToMany(Role::class);
    }

    public function hasPermission($permission)
    {
        foreach ($this->roles as $role) {
            if ($role->hasPermission($permission)) {
                return true;
            }
        }
        return false;
    }

    public function givePermission($permission)
    {
        $permissionModel = Permission::where('name', $permission)->first();
        if (!$permissionModel) {
            throw new Exception("Permission {$permission} does not exist.");
        }
        $this->permissions()->sync($permissionModel, false);
    }

    public function revokePermission($permission)
    {
        $permissionModel = Permission::where('name', $permission)->first();
        if (!$permissionModel) {
            throw new Exception("Permission {$permission} does not exist.");
        }
        $this->permissions()->detach($permissionModel);
    }

    public function permissions()
    {
        return $this->belongsToMany(Permission::class, 'user_permissions');
    }
}

3. Define the role model
In the Hyperf framework, We also need to define a role model, which is used to manage roles and permissions. Likewise, we can create a role model by inheriting the HyperfDatabaseModelModel class. Execute the following command in the terminal to generate the role model:

php bin/hyperf.php gen:model Role

Then add the following code to the generated role model file:

namespace AppModel;

use HyperfDbConnectionModelModel;

class Role extends Model
{
    protected $guarded = [];

    public function users()
    {
        return $this->belongsToMany(User::class);
    }

    public function permissions()
    {
        return $this->belongsToMany(Permission::class);
    }

    public function hasPermission($permission)
    {
        return $this->permissions->contains('name', $permission);
    }

    public function givePermission($permission)
    {
        $permissionModel = Permission::where('name', $permission)->first();
        if (!$permissionModel) {
            throw new Exception("Permission {$permission} does not exist.");
        }
        $this->permissions()->sync($permissionModel, false);
    }

    public function revokePermission($permission)
    {
        $permissionModel = Permission::where('name', $permission)->first();
        if (!$permissionModel) {
            throw new Exception("Permission {$permission} does not exist.");
        }
        $this->permissions()->detach($permissionModel);
    }
}

4. Define the permission model
In the Hyperf framework, We also need to define a permission model, which is used to manage permission information. Likewise, we can create a permission model by inheriting the HyperfDatabaseModelModel class. Execute the following command in the terminal to generate the permission model:

php bin/hyperf.php gen:model Permission

Then add the following code to the generated permission model file:

namespace AppModel;

use HyperfDbConnectionModelModel;

class Permission extends Model
{
    protected $guarded = [];

    public function roles()
    {
        return $this->belongsToMany(Role::class);
    }
}

5. Define permission middleware
Next, we You need to create a permission middleware to check whether the user has sufficient permissions to access a route. Execute the following command in the terminal to generate middleware:

php bin/hyperf.php gen:middleware PermissionMiddleware

Then add the following code to the generated middleware file:

namespace AppMiddleware;

use HyperfHttpMessageStreamSwooleStream;
use HyperfHttpServerContractRequestInterface;
use HyperfUtilsContext;
use PsrContainerContainerInterface;
use PsrHttpMessageResponseInterface;
use PsrHttpServerMiddlewareInterface;
use PsrHttpServerRequestHandlerInterface;

class PermissionMiddleware implements MiddlewareInterface
{
    protected $container;

    protected $request;

    public function __construct(ContainerInterface $container, RequestInterface $request)
    {
        $this->container = $container;
        $this->request = $request;
    }

    public function process($request, RequestHandlerInterface $handler): ResponseInterface
    {
        $user = $this->request->getAttribute('user');
        $permissions = $this->request->route->permission;

        if ($user && $user->hasPermission($permissions)) {
            return $handler->handle($request);
        }

        return $this->response(403, 'Forbidden');
    }

    protected function response($code, $message)
    {
        $data = [
            'code' => $code,
            'message' => $message,
        ];

        return Context::get(ResponseInterface::class)->withBody(new SwooleStream(json_encode($data)));
    }
}

6. Use permission middleware
In the routing definition , we can set the corresponding permission middleware for the route by using ->middleware('permission:xxx'). Execute the following command in the terminal to generate a routing file:

php bin/hyperf.php gen:controller PermissionController

Then add the following code to the generated routing file:

namespace AppController;

use AppMiddlewarePermissionMiddleware;
use HyperfHttpServerAnnotationController;
use HyperfHttpServerAnnotationMiddleware;
use HyperfHttpServerAnnotationRequestMapping;

/**
 * @Controller
 * @Middleware(PermissionMiddleware::class)
 */
class PermissionController
{
    /**
     * @RequestMapping(path="/permission", methods="get")
     * @Middleware("permission:create_post")
     */
    public function createPost()
    {
        // 處理創(chuàng)建文章的邏輯
    }

    /**
     * @RequestMapping(path="/permission", methods="get")
     * @Middleware("permission:edit_post")
     */
    public function editPost()
    {
        // 處理編輯文章的邏輯
    }

    /**
     * @RequestMapping(path="/permission", methods="get")
     * @Middleware("permission:delete_post")
     */
    public function deletePost()
    {
        // 處理刪除文章的邏輯
    }
}

7. Usage examples
Where permission control is required , we can check whether the user has sufficient permissions through the following methods:

$user = User::find(1);

if ($user->hasPermission('edit_post')) {
    // 給用戶權(quán)限來編輯文章
} else {
    // 權(quán)限不足
}

8. Summary
This article introduces the detailed steps of how to use the Hyperf framework for permission control, and provides specific code examples. By using the permission management functions provided by the Hyperf framework, we can easily implement flexible permission control functions for our applications. I hope this article is helpful to you, thank you for reading!

The above is the detailed content of How to use the Hyperf framework for permission control. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use the Hyperf framework for cross-domain request processing How to use the Hyperf framework for cross-domain request processing Oct 20, 2023 pm 01:09 PM

How to use the Hyperf framework for cross-domain request processing Introduction: In modern network application development, cross-domain requests have become a common requirement. In order to ensure the separation of front-end and back-end development and improve user experience, it has become particularly important to use the Hyperf framework for cross-domain request processing. This article will introduce how to use the Hyperf framework for cross-domain request processing and provide specific code examples. 1. What is a cross-domain request? Cross-domain requests refer to JavaScript running on the browser through XMLHttpReques.

How to implement permission control and user management in uniapp How to implement permission control and user management in uniapp Oct 20, 2023 am 11:15 AM

How to implement permission control and user management in uniapp With the development of mobile applications, permission control and user management have become an important part of application development. In uniapp, we can use some practical methods to implement these two functions and improve the security and user experience of the application. This article will introduce how to implement permission control and user management in uniapp, and provide some specific code examples for reference. 1. Permission Control Permission control refers to setting different operating permissions for different users or user groups in an application to protect the application.

How to use Hyperf framework for file storage How to use Hyperf framework for file storage Oct 25, 2023 pm 12:34 PM

How to use the Hyperf framework for file storage requires specific code examples. Hyperf is a high-performance PHP framework developed based on the Swoole extension. It has powerful functions such as coroutines, dependency injection, AOP, middleware, and event management. It is suitable for building high-performance, Flexible and scalable web applications and microservices. In actual projects, we often need to store and manage files. The Hyperf framework provides some convenient components and tools to help us simplify file storage operations. This article will introduce how to use

How to use the Hyperf framework for code analysis How to use the Hyperf framework for code analysis Oct 25, 2023 am 11:12 AM

How to use the Hyperf framework for code analysis requires specific code examples Introduction: In the software development process, the quality and performance of the code need to be properly analyzed and evaluated. As a high-performance PHP development framework, the Hyperf framework provides a wealth of tools and functions to help developers conduct code analysis. This article will introduce how to use the Hyperf framework for code analysis, and illustrate it with specific code examples. 1. Selection of code analysis tools The Hyperf framework provides some practical tools.

User management and permission control in Laravel: implementing multiple users and role assignments User management and permission control in Laravel: implementing multiple users and role assignments Aug 12, 2023 pm 02:57 PM

User management and permission control in Laravel: Implementing multi-user and role assignment Introduction: In modern web applications, user management and permission control are one of the very important functions. Laravel, as a popular PHP framework, provides powerful and flexible tools to implement permission control for multiple users and role assignments. This article will introduce how to implement user management and permission control functions in Laravel, and provide relevant code examples. 1. Installation and configuration First, implement user management in Laravel

How to use the Hyperf framework for log management How to use the Hyperf framework for log management Oct 25, 2023 am 09:15 AM

How to use the Hyperf framework for log management Introduction: Hyerpf is a high-performance, highly flexible coroutine framework based on the PHP language, with rich components and functions. Log management is an essential part of any project. This article will introduce how to use the Hyperf framework for log management and provide specific code examples. 1. Install the Hyperf framework First, we need to install the Hyperf framework. It can be installed through Composer, open the command line tool and enter the following command

Best Practices for Laravel Permissions Features: How to Correctly Control User Permissions Best Practices for Laravel Permissions Features: How to Correctly Control User Permissions Nov 02, 2023 pm 12:32 PM

Best practices for Laravel permission functions: How to correctly control user permissions requires specific code examples Introduction: Laravel is a very powerful and popular PHP framework that provides many functions and tools to help us develop efficient and secure web applications. One important feature is permission control, which restricts user access to different parts of the application based on their roles and permissions. Proper permission control is a key component of any web application to protect sensitive data and functionality from unauthorized access

How to use Hyperf framework for JWT authentication How to use Hyperf framework for JWT authentication Oct 24, 2023 pm 12:36 PM

How to use the Hyperf framework for JWT authentication Introduction: Hyperf is a high-performance coroutine framework based on Swoole, which provides rich functions and flexible scalability. JWT (JSONWebToken) is an open standard for authenticating and transmitting information. In this article, we will introduce how to use JWT authentication in the Hyperf framework and provide specific code examples. 1. Install dependency packages First, we need to install hyperf/jwt and lcobucci/jw

See all articles