PHP code example of zeaven / laravel-easy-suit

1. Go to this page and download the library: Download zeaven/laravel-easy-suit 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/ */

    

zeaven / laravel-easy-suit example snippets


    public function boot()
    {
        $this->configureRateLimiting();

        $this->routes(function () {
            Route::configRoute('api', 'api');
            Route::configRoute('web');
        });
    }

    Route::macro(
        'configRoute',
        function (string $name, string $prefix = '/', array $middleware = []) {
            $namespace = "App\\Http\\Controllers\\" . ucfirst($name);
            Route::prefix($prefix)
                ->middleware(empty($middleware) ? $name : $middleware)
                ->namespace($namespace)
                ->domain(config('app.url'))
                ->group(base_path("routes/{$name}.php"));
        }
    );

use Zeaven\EasySuit\Http\Requests\BaseRequest;

class LoginRequest extends BaseRequest
{
    /**
     * 返回参数验证规则.
     *
     * @return array
     */
    protected function rule(): array
    {
        return [
            // 用户名
            'username' => ['rule' => '

[$username, $password] = $request->values();
// 或
[$username] = $request->values(['username']);
// 或
[$password, $username] = $request->values(['password', 'username']);

// 获取key/value数组
$params = $request->params();
// $params = ['username' => 'xxx', 'password' => 'xxx']
// 或
$params = $request->params(['username']);
// 或
// $params = ['username' => 'xxx']
$params = $request->params(['username', 'password']);
// $params = ['username' => 'xxx', 'password' => 'xxx']

[
    'username' => [
        'rule' => 'ype' => 'string',
        'as' => 'login_name'
    ],
    'remember' => true, // 等同于 'remember' => ['default' => true]
    'password'  // 等同于‘password’ => ['default' => null]
]

    protected $middlewareGroups = [
        'web' => [
        ],

        'api' => [
            \Zeaven\EasySuit\Http\Middleware\GlobalResponse::class,
            // \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
            'throttle:api',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],
    ];


'global_response' => [
    'fields' => [
        'code' => 'code',
        'data' => 'data',
        'message' => 'msg',
        'error' => false, // error只有在debug环境下有效
    ],
    'exclude' => [
        'horizon/*',
        'laravel-websockets/*',
        'broadcasting/*',
        '*/export/*',
        '*/pusher/auth',
        '*/pusher/auth',
        'web/*',
    ]
],

/**
 * 错误码定义样例,请不要在这里定义错误码!应在对应的语言包目录下创建error_code.php文件!
 * 错误码以十六进制方式定义,如f00000:
 * -- 第1位:项目 f全局、1~e自行分项目,如1ios、2android、3web、4小程序
 * -- 第2-3位:模块 00全局、其他数字自行定义,如01登录、02订单、03钱包
 * -- 第4-5位:错误码,如00~ff都可以使用
 * -- 第6位:提示码,0忽略错误、1客户端弹窗提示、2客户端toast提示
 * 出现error_code=0,则后台未知错误
 *
 * 比如定义ios端登录模块错误码: 101012 => '用户名错误', 101022 => '用户密码错误'
 */

return [
    '401'    => '未授权',
    '500'    => '查询出错',
    'f00002' => 'token已过期',
    'f00012' => '用户不存在',
    'f00022' => 'token无效',
    'f00032' => '缺少登录信息',
];

// 直接抛出错误码
throw_e(0x000001);
throw_e(401);
// 抛出异常信息
throw_e('异常信息');
// 指定错误信息和错误码
throw_e('异常信息', 0x000001);
// 空条件抛出
throw_empty($user, 0x000001);   // $user变量为空则抛出异常
throw_empty($user, '异常信息');   // 同上
throw_empty($user, '异常信息', 0x000001);   // 同上
// 判断条件抛出
throw_on($user->status === -1, 0x000001);
// 或
throw_on($user->status === -1, '异常信息');
throw_on($user->status === -1, '异常信息', 0x000001);

    protected $middlewareGroups = [
        'web' => [
        ],

        'api' => [
            \Zeaven\EasySuit\Annotations\AnnoLogMiddleware::class,
            // \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
            'throttle:api',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],
    ];


    'anno_log' => [
        'enable' => env('EASY_SUIT_ANNO_LOG', true),
        'handler' => MyAnnoLogHandler::class
    ],

    use Zeaven\EasySuit\Annotations\AnnoLog; // 必须引用注解命名空间

    #[AnnoLog(tpl:"{mobile},审核提现,订单号{order_no},签名{sign}")]
    public function index(TestRequest $request)
    {
        // 设置日志模板变量
        anno_log(['order_no' => 'test', 'sign' => 'sign']);
        // 或
        anno_log('order_no', 'test');
        anno_log('sign', 'sign');
    }

    'auth' => [
        'sanctum' => true,
        'jwt' => [
            'enable' => true,
            'guard' => 'jwt'
        ],
    ],

>     'expiration' => 20160,  // 两周过期时间
>     'refresh_ttl' => 60,    // 一个小时刷新一次token
>     'refresh_grace_ttl' => 5, // 刷新token的灰色时间,防止同一token并发多个请求刷新多次
>     'remove_refresh_expire_token' => true,  // 是否移除已刷新的token
> 

Route::middleware('auth:sanctum')->group(function () {
    // 你的路由
});

composer 

    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
        'jwt' => [
            'driver' => 'jwt',
            'provider' => 'users',
        ]
    ],


Route::middleware('auth:jwt')->group(function () {
    // 你的路由
});

php artisan gen:mapper user/info
// 将在路径生成文件 App/Http/ResponseMappers/User/InfoMapper.php


namespace App\Http\ResponseMappers\User;

use Zeaven\EasySuit\Http\ResponseMappers\BaseResponseMapper;

class InfoMapper extends BaseResponseMapper
{
    protected $mapper = [];

    protected $hidden = [];
}

$article = [
    'title' => 'xxx',
    'content' => 'xxx',
    'tags' => '',
    'comments' => [
        [
            'user' => ['username' => '用户A', 'vip' => 'x', 'mobile' => 'xxx'],
            'content' => 'xxx'
        ],
    ],
    'category' => ['name' => 'xxx']
    'user' => ['username' => '作者', 'vip' => 'x']
];


class InfoMapper extends BaseResponseMapper
{
    protected $mapper = [
        // 将模型中category对象的name属性,转换为JSON数据的category_name字段
        'category_name': 'category.name',
        // 将模型中user对象的所有性情展开到JSON对象下,并添加"poster_"前缀
        // 将"poster"改为"_",则不添加前缀,直接把user对象属性复制到JSON对象下
        'poster' => 'user.*',
        // 对模型中comments数组的每一个对象的mobile属性值,传递给指定handler处理后返回
        // Handler可指定多个
        'comments.*' => ['user.mobile', MobileHandler::class]
    ];

    protected $hidden = [
        "tags",
        "comments.*.user.vip",
        "user",
        "category"
    ];
}

// MobileHandler
class MobileHandler
{
    // $value指定的属性值/或上一个handler返回值, $data为当前属性的对象数据,如上面的配置即为comment的user数据
    public function handle($value, $data)
    {
        return '';
    }
}

return new InfoMapper($article);

    'model' => [
        // 或 'simple_pagination' => '自定义分页对象'
        'simple_pagination' => true,
        'extension' => true
    ]


A::with('b.c.d')
// 等同于
A::withs('b', 'c', 'd')
// 等同于
A::withs(['b', 'c', 'd'])

// 加载关系模型时选择字段
A::withs('b:col1,col2,col3', 'c', 'd:col1,col2')
// 等同于
A::withs(['b:col1,col2,col3', 'c', 'd:col1,col2'])

// 载关系模型时增加筛选条件
A::withs([
    'b:col1,col2,col3' => fn($q) => $q->where('col1', 'xxx'),
    'c' => fn($q) => $q->select('col1','col2','col3'),
    'd:col1,col2' => fn($q) => $q->orderBy('col3')
])

$fields = [];
A::selectWhen($fields)->get();

$options = ['col1' => 1, 'col2' => 'xxx'];
A::whereWhen($options)->get();

$a = 1;
$col1 = 'xxx';
A::filledWhen($a, $col1, function($q, $a, $col1) => {
    $q->where('col1', $col1)->where('col2', $a);
})->get();

A::betweenWhen('col1', 1, 10)->get();
// select * from a where col1 between 1, 10

A::betweenWhen('col1', 1)->get();
// select * from a where col1 >= 1

A::betweenWhen('col1', null, 10)->get();
// select * from a where col1 <= 10


A::likeWhen('col1', 'xyz')->get();
// select * from a where col1 like '%xyz%'
bash
php artisan vendor:publish --provider=Zeaven\\EasySuit\\ServiceProvider