承接 artificertech/eloquent-attribute-middleware 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

artificertech/eloquent-attribute-middleware

Composer 安装命令:

composer require artificertech/eloquent-attribute-middleware

包简介

:package_description

README 文档

README

Latest Version on Packagist Total Downloads Build Status StyleCI

This package enables you to define middleware classes for your Eloquent model accessors and mutators using php 8 Attributes. This allows you to reuse complex code for your computed attributes. Take a look at contributing.md to see a to do list.

Requirements

php ^8.0, Laravel ^8

Installation

Via Composer

composer require artificertech/eloquent-attribute-middleware

Usage

Accessors

create your accessor middleware class using laravel artisan

php artisan make:accessor MyAccessor

Configure your accessor middleware. Accessor middlware should modify the response of the $next() callback and return the modified value.

namespace App\Accessors;

use Artificertech\EloquentAttributeMiddleware\Accessors\Accessor;
use Attribute;
use Closure;

#[Attribute(Attribute::TARGET_METHOD)]
class Upper extends Accessor
{
    /**
     * Run the mutator on the specified model attribute value
     *
     * @param $key the attribute name
     * @param $model the model this attribute is being set for
     * @param $next the next middleware function to call
     * @return mixed
     */
    public function __invoke($key, $model, Closure $next)
    {
        return Str::upper($next());
    }
}

Add the middleware functionality to your Eloquent Model

...
use App\Accessors\Upper;
use Artificertech\EloquentAttributeMiddleware\Models\Concerns\HasAttributeMiddleware;
...
class User extends Model
{
    use HasAttributeMiddleware;
    ...

    #[Upper]
    public function getNameAttribute($value)
    {
        return $value;
    }
}

Now any time you retrieve the name attribute it will be Uppercase

Execution Order

Accessors run in order of definition. In the following example the user 'name' attribute is stored in the database as 'Cole Shirley'

#[Attribute(Attribute::TARGET_METHOD)]
class Upper extends Accessor
{
    /**
     * make the value uppercase
     *
     * @param $key the attribute name
     * @param $model the model this attribute is being set for
     * @param $next the next middleware function to call
     * @return mixed
     */
    public function __invoke($key, $model, Closure $next)
    {
        return Str::upper($next());
    }
}
...
#[Attribute(Attribute::TARGET_METHOD)]
class AppendTestString extends Accessor
{
    /**
     * append _test to the value
     * 
     * @param $key the attribute name
     * @param $model the model this attribute is being set for
     * @param $next the next middleware function to call
     * @return mixed
     */
    public function __invoke($key, $model, Closure $next)
    {
        return $next() . '_test';
    }
}
...
use App\Accessors\Upper;
use App\Accessors\AppendTestString;
use Artificertech\EloquentAttributeMiddleware\Models\Concerns\HasAttributeMiddleware;
...
class User extends Model
{
    use HasAttributeMiddleware;
    ...

    #[Upper]
    #[AppendTestString]
    public function getNameAttribute($value)
    {
        return $value;
    }
}

$user =  User::find(1);

$user->name; // 'COLE SHIRLEY_TEST'

Execution order:

  1. the Upper __invoke method is called first which retrieves the value of the next callback
  2. the AppendTestString __invoke method is then called which retireves the value of the next callback
  3. the getNameAttribute method is called with the value 'Cole Shirley' from the stored model attributes
  4. that value is passed back to AppendTestString which then concatenates '_test' onto the value
  5. the modified string is passed back to Upper which makes the entire string uppercase
  6. the finalized string is passed back to the implemenation

Mutators

create your mutator middleware class using laravel artisan

php artisan make:mutator MyMutator

Configure your mutator middleware. Mutator middlware should modify $value parameter before passing it to the $next() callback

namespace App\Mutators;

use Artificertech\EloquentAttributeMiddleware\Mutators\Mutator;
use Attribute;
use Closure;

#[Attribute(Attribute::TARGET_METHOD)]
class Lower extends Mutator
{
    /**
     * make the value lowercase
     *
     * @param $value the value of the attribute to set
     * @param $key the attribute name
     * @param $model the model this attribute is being set for
     * @param $next the next middleware function to call
     * @return mixed
     */
    public function __invoke($value, $key, $model, Closure $next)
    {
        return $next(Str::lower($value));
    }
}

Add the middleware functionality to your Eloquent Model

...
use App\Mutators\Lower;
use Artificertech\EloquentAttributeMiddleware\Models\Concerns\HasAttributeMiddleware;
...
class User extends Model
{
    use HasAttributeMiddleware;
    ...

    #[Lower]
    public function setNameAttribute($value)
    {
        $this->attributes['name'] = $value;
    }
}

Now when you set the name attribute it will be lowercased

Execution Order

Mutators run in order of definition

class Lower extends Mutator
{
    /**
     * make the value lowercase
     *
     * @param $value the value of the attribute to set
     * @param $key the attribute name
     * @param $model the model this attribute is being set for
     * @param $next the next middleware function to call
     * @return mixed
     */
    public function __invoke($value, $key, $model, Closure $next)
    {
        return $next(Str::lower($value));
    }
}
...
class WithoutExtraWhitespace extends Mutator
{
    /**
     * make the value lowercase
     *
     * @param $value the value of the attribute to set
     * @param $key the attribute name
     * @param $model the model this attribute is being set for
     * @param $next the next middleware function to call
     * @return mixed
     */
    public function __invoke($value, $key, $model, Closure $next)
    {
        return $next(preg_replace('/\s+/', ' ', $value));
    }
}
...
use App\Mutators\Lower;
use App\Mutators\WithoutExtraWhitespace;
use Artificertech\EloquentAttributeMiddleware\Models\Concerns\HasAttributeMiddleware;
...
class User extends Model
{
    use HasAttributeMiddleware;
    ...

    #[Lower]
    #[WithoutExtraWhitespace]
    public function setNameAttribute($value)
    {
        $this->attributes['name'] = $value;
    }
}

$user = new User;

$user->name = 'Cole   Shirley'; // stored as 'cole shirley'

Execution order:

  1. the Lower __invoke method is called first with the value 'Cole Shirley'
  2. the WithoutExtraWhitespace __invoke method is called with the value 'cole shirley'
  3. the setNameAttribute is called with the value 'cole shirley'
  4. if the setNameAttribute has a return value it is passed back to the implementation

Practical example: Caching model info from api

For most situations you should be able to use normal accessor and mutator functionality. However if you find yourself setting up complicated accessors or mutators repeatedly you may consider extracting that functionality into accessor and mutator middleware. A great example is if you want to cache data related to a model from an external api

namespace App\Mutators;

use Artificertech\EloquentAttributeMiddleware\Mutators\Mutator;
use Attribute;
use Closure;

#[Attribute(Attribute::TARGET_METHOD)]
class Cached extends Mutator
{
    /**
     * Check the cache for the attribute 
     * 
     * @param $key the attribute name
     * @param $model the model this attribute is being set for
     * @param $next the next middleware function to call
     * @return mixed
     */
    public function __invoke($key, $model, Closure $next)
    {
        return Cache::rememberForever($model::class . ":{$model->getKey()}:{$key}", function () use ($value, $next) {
            return $next();
        });
    }
}

...
namespace App\Models;

use App\Mutators\Cached;
use Artificertech\EloquentAttributeMiddleware\Models\Concerns\HasAttributeMiddleware;
...
class User extends Model
{
    use HasAttributeMiddleware;
    ...

    #[Cached]
    public function getApiDataAttribute()
    {
        return Http::get('https://example.com/api/users/', ['name' => $this->name]);
    }
}

Change log

Please see the changelog for more information on what has changed recently.

Testing

composer test

Contributing

Please see contributing.md for details and a todolist.

Security

If you discover any security related issues, please email author@email.com instead of using the issue tracker.

Credits

License

MIT. Please see the license file for more information.

artificertech/eloquent-attribute-middleware 适用场景与选型建议

artificertech/eloquent-attribute-middleware 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 131 次下载、GitHub Stars 达 0, 最近一次更新时间为 2021 年 12 月 13 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「laravel」 「EloquentAttributeMiddleware」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 artificertech/eloquent-attribute-middleware 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 artificertech/eloquent-attribute-middleware 我们能提供哪些服务?
定制开发 / 二次开发

基于 artificertech/eloquent-attribute-middleware 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 131
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 0
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2021-12-13