sonleu/barrier

这是一个处理控制器中预条件的小型包

v1.0.0 2020-09-09 10:00 UTC

This package is auto-updated.

Last update: 2024-09-09 19:20:51 UTC


README

此包用于在控制器中实现任何工作之前处理预条件,同时使用Laravel内置的中间件和表单请求。

Latest Stable Version Total Downloads Latest Unstable Version License

目录

安装

Composer

执行以下命令以获取包的最新版本

composer require sonleu/barrier

用法

生成器

通过生成器轻松创建您的障碍。

命令

php artisan make:barrier MyBarrier

这将创建一个位于App/Barriers文件夹中的Barrier文件。

示例

namespace App\Barriers;

use SonLeu\Barrier\BarrierInterface;

class FooBarrier implements BarrierInterface
{
    protected $argument;

    // You can pass any argument here
    public function __construct ($argument) 
    {
        $this->argument = $argument;
    }

    /**
     * @return bool
     */
    public function passes(): bool
    {
        if (SOMETHING_SHOULD_NOT_BE_ALLOWED) {
            return false;
        }

        return true;
    }

    /**
     * @return string
     */
    public function message(): string
    {
        return 'Your message if not pass';
    }
}

使用方法

您可以在控制器内的任何地方使用障碍,甚至在您的业务逻辑层。

它应该放在您的逻辑之上。

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use SonLeu\Barrier\HasBarrier;
use SonLeu\Barrier\Exceptions\BarrierNotPassedException;

class FooController extends Controller 
{
    use HasBarrier;

    public function bar(Request $request)
    {
        try {
            $this->barrier([
                new CheckIfTuesdayBarrier(),
                new CheckVirginityBarrier(auth()->user()),
            ]);
        } catch (BarrierNotPassedException $e) {
            return back()->with('error', $e->getMessage());
        }

        //TODO: your logic
    }
}