PHP code example of yiisoft / access

1. Go to this page and download the library: Download yiisoft/access library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

yiisoft / access example snippets


namespace App;

use Yiisoft\Access\AccessCheckerInterface;

class UserService
{
    private AccessCheckerInterface $accessChecker;
    
    public function __construct(AccessCheckerInterface $accessChecker)
    {
        $this->accessChecker = $accessChecker;
    }
    
    public function can(string $permissionName, array $parameters = []): bool
    {
        return $this->accessChecker->userHasPermission(
            $this
                ->getCurrentUser()
                ->getId(),
            $permissionName,
            $parameters
        );
    }
    
    public function getCurrentUser(): User
    {
        // ...
    }
}

public function actionList(UserService $userService)
{
    if (!$userService->can('list_posts')) {
        // access denied
    }

    // list posts
}