spotonlive / sl-assertions
Laravel 5.1 的断言
v0.0.2
2015-09-18 08:29 UTC
Requires
- php: >=5.4.0
Requires (Dev)
- codeclimate/php-test-reporter: dev-master
- laravel/framework: ~5.1
- phpmd/phpmd: 1.4.*
- phpunit/phpunit: ~4.0
- squizlabs/php_codesniffer: 2.*
This package is not auto-updated.
Last update: 2024-09-14 18:25:59 UTC
README
此包正在开发中
配置
安装
运行 $ composer require spotonlive/sl-assertions
config/app.php
将提供者和辅助别名插入您的应用程序配置
'providers' => [ \SpotOnLive\Assertions\Providers\Services\AssertionServiceProvider::class, \SpotOnLive\Assertions\Providers\Helpers\AssertionHelperProvider::class, ] 'aliases' => [ 'AssertionHelper' => \SpotOnLive\Assertions\Facades\Helpers\AssertionHelperFacade::class, ]
配置
运行 $ php artisan vendor:publish
以创建配置文件。现在在 config/assertions.php
中可用配置文件。
断言
要创建新示例,请创建一个实现断言接口的新断言文件。例如
EditAssertion.php
<?php namespace App\Assertions\Users; use SpotOnLive\Assertions\AssertionInterface; use App\Entities\User; class EditAssertion implements AssertionInterface { /** * @param User $user * @param array $data * @return bool */ public function assert($user, array $data = []) { /** @var User $userToEdit */ $userToEdit = $data['user']; return $user == $userToEdit || $user->hasRole(['superadmin', 'admin']); } }
然后在您的配置文件中注册断言
config/assertions.php
<?php return [ 'users.edit' => \App\Assertions\Users\EditAssertion::class, ];
用法
服务
通过注入 AssertionService
使用断言服务。
app::make('AssertionService')
示例
<?php namespace App\Controllers; use \SpotOnLive\Assertions\Services\AssertionServiceInterface; class Controller { /** @var AssertionServiceInterface **/ protected $assertionService; public function __construct(AssertionServiceInterface $assertionService) { $this->assertionService = $assertionService; } public function admin() { if (!$this->assertionService->isGranted('admin.page', Auth::user())) { return redirect()->route('not-granted'); } return view('admin.page'); } }
辅助工具
直接在您的视图中使用 AssertionHelper
。
示例: view.blade.php
@if(AssertionHelper::isGranted('user.edit', Auth::user(), ['user' => $user])) <a href="{{URL::route('user.edit')}}">{{_('Edit user')}}</a> @endif