imanghafoori/laravel-middlewarize

在您的应用程序中对任何方法调用使用laravel中间件

v1.1.11 2024-05-24 09:04 UTC

This package is auto-updated.

Last update: 2024-09-24 10:03:57 UTC


README

Laravel Middlewarize

🎀 Laravel应用中的责任链设计模式 🎀


Onion

Maintainability Quality Score Latest Stable Version Code Coverage Software License

您可以使用中间件来装饰任何对象上的任何方法调用。

// Normal Call:
$myObj->myMethod();

// Decorated Call:
$myObj
    ->middlewares([...])
    ->myMethod():

🔥 安装

composer require imanghafoori/laravel-middlewarize

▶️ 如何使用

\Imanghafoori\Middlewarize\Middlewarable 特性应用到您的类上。

例如,考虑一个简单的仓库类

class UserRepository
{
    use Middlewarable;     //   <----  Use "Middlewarable" trait on your class
    
    public function find($id) 
    {
        return User::find($id);   //   <----  we wanna cache it, right?
    }
    ...
}

▶️ 定义中间件

class CacheMiddleware
{
    public function handle($data, $next, $key, $ttl)
    {
        // 1. This part runs before method call
        if (Cache::has($key)) {
            return Cache::get($key);
        }
        
        $value = $next($data);  // <--- 2. Runs the actual method
        
       
        Cache::put($key, $value, $ttl);  // <-- 3. This part runs after method
        
        return $value;
    }
}

由于中间件是由laravel容器解析的,因此您可以传递任何抽象字符串作为中间件并在IOC中绑定它

public function boot()
{
    app()->singleton('cacher', CacheMiddleware::class);  // <---- Optional step
}

▶️ 使用中间件

清理后的控制器将看起来像这样

public function show($id, UserRepository $repo)
{
    $cachedUser = $repo
        ->middleware('cacher:fooKey,60')
        ->find($id);
}

简单易懂?

您完全将缓存关注点分离到一个新的类中。

那么让我们比较...

之前

在使用中间件之前,我们的代码是这样的

public function show($id, UserRepository $repo)
{
    if (Cache::has('user.'.$id)) {
        return Cache::get('user.'.$id); // <--- extra fluff around ->find($id)
    }
        
    $value = $repo->find($id);  //   <--- important method call here.

    Cache::put('user.'.$id, $value, 60); // <--- extra fluff around ->find($id)
        
    return $value;
}

▶️ 覆盖默认中间件方法

public function show($id, UserRepository $repo)
{
    $cachedUser = $repo
        ->middleware('cacher@MyHandle1:fooKey,60')  // <--- Overrides default "handle" method name
        ->find($id);
}

▶️ 多个中间件

public function show($id, UserRepository $repo)
{
    $cachedUser = $repo->middleware(['middle1', 'middle2', 'middle3'])->find($id);
}

执行顺序是这样的

开始 ===> ( 中间1 -> 中间2 -> 中间_3 ( find ) 中间3 -> 中间2 -> 中间1 ) ===> 结果 !!!

▶️ 在外观上使用中间件?!

您想使用外观来调用仓库吗?没问题。

$cachedUser = UserRepositoryFacade::middleware('cacher:fooKey,60 seconds')->find($id);

▶️ 对象作为中间件

您还可以在更复杂的场景中使用对象作为中间件。

$obj = new CacheMiddleware('myCacheKey', etc...);   //   <---- you send depedencies to it.

$repo->middleware($obj)->find($id);

▶️ 静态方法上的中间件

User::find($id);       //  <--- Sample static method call

User::middlewared('cache:key,10')->find($id); // <--- you can have a decorated call

// also you must put 'middlewarable' trait on User model.

▶️ 测试

如前所述,中间件是在IOC中解析的,这意味着您可以在运行测试时轻松地替换它们。

class NullCacheMiddleware
{
    public function handle($data, $next, $key, $ttl)
    {
        return $next($data); // <--- this "null middleware" does nothing.
    }
}


public function testSomeThing()
{
    app()->singleton('cacher', NullCacheMiddleware::class);  // <--- this causes to replace the cache middleware
    
    $this->get('/home');
}

在这里,我们在测试运行时使中间件“什么都不做”。

▶️ 如果您的从方法抛出异常会发生什么?

如果您在方法中抛出异常,则后置中间件仍然会执行,而 $value = $next(data) 的值将是抛出的异常。当所有中间件执行完毕后,异常将被重新抛出。

🙋 贡献

如果您发现了一个问题,或者有更好的方法来做某事,请随时打开一个问题或拉取请求。

⭐ 您的星标让我们做得更多 ⭐

一如既往,如果您认为这个包很有用,并希望鼓励我们维护和改进它,只需按一下星标按钮即可表达您的意愿。

作者的其他作品

Laravel Widgetize

💎 一个简单但强大的包,为您提供了更好的laravel应用程序结构和缓存机会。

Laravel HeyMan

💎 它允许您编写表达式的代码来进行授权、验证和身份验证。

Laravel Terminator

💎 一个简单但强大的包,为您提供重构控制器的机会。

Laravel AnyPass

💎 它允许您在本地环境中使用任何密码登录。

Eloquent Relativity

💎 它允许您解耦Eloquent模型以实现模块化结构。

Logic will get you from a to z, imagination will take you everywhere.

"Albert Einstein"