PHP code example of yesccx / better-laravel

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

    

yesccx / better-laravel example snippets


$foo()->getData(1, 0); // return: null

$foo(-1)->getData(1, 0); // return: -1

$list = User::query()->where('status', 1)->customPaginate();

$data = request()->fetchMany([
    'user_id/d' => 0,
    'phone/s' => '',

    // 不指定默认值时,默认为null
    'summary/s'
]);

# gray environment

GrayEnvironment::instance()->verified();
// true

ProdEnvironment::instance()->verified();
// false
 shell
> php artisan better-laravel:install
 php


namespace App\Exceptions;

use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Yesccx\BetterLaravel\Exceptions\ExceptionHandlerManager;

class Handler extends ExceptionHandler
{
    /**
     * Register the exception handling callbacks for the application.
     *
     * @return void
     */
    public function register()
    {
        ExceptionHandlerManager::register($this);

        // Do something....
    }
}
 php


// routes/modules/user.php

use Illuminate\Support\Facades\Route;

Route::group([
    'prefix' => 'user'
], function() {
    // Create user
    Route::get('create', [\App\Http\Controller\UserController::class, 'create']);

    // Get userinfo
    Route::get('info', [\App\Http\Controller\UserController::class, 'info']);
});
 php


// routes/modules/content.php

use Illuminate\Support\Facades\Route;

Route::group([
    'prefix' => 'content'
], function() {
    // Get list
    Route::get('list', [\App\Http\Controller\ContentController::class, 'list']);

    // Get info
    Route::get('info', [\App\Http\Controller\ContentController::class, 'info']);
});
 shell
> php artisan migrate:to-sql --path=database/migrations/2023_03_15_172792_create_users_table

# --------------------------------------------------
# -- Input: database/migrations/2023_03_15_172792_create_users_table.php / up
# -- Datetime: 2023-04-03 10:18:14
# -- Total: 1
# --------------------------------------------------
# -- Migrate:2023_03_15_172792_create_users_table.php

# create table `users` (`id` bigint unsigned not null auto_increment primary key comment '自增id') default character set utf8mb4 collate 'utf8mb4_unicode_ci';

# ALTER TABLE `users` comment '用户表';
# --------------------------------------------------
 shell
# 处理迁移文件名中含有关键字'2023_03_15'的迁移文件
> php artisan migrate:to-sql --path=2023_03_15


# 处理迁移文件名中含有关键字'user'的迁移文件
> php artisan migrate:to-sql --path=user
 shell
> php artisan migrate:to-sql --path=2023_03_15 --type=down
 shell
> php artisan migrate:to-sql --path=2023_03_15 >> migrate.sql
 php


namespace App\Exceptions;

use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Yesccx\BetterLaravel\Exceptions\ExceptionHandlerManager;

class Handler extends ExceptionHandler
{
    /**
     * Register the exception handling callbacks for the application.
     *
     * @return void
     */
    public function register()
    {
        ExceptionHandlerManager::register($this);
    }
}
 php
class UserService {
    use InstanceMake;

    public function __construct(
        public int $id = 0
    ) {}
};

UserService::make(['id' => 1]);
 php
class UserService {
    use InstanceMake;

    public function __construct(
        public UserModel $model
    ) {}
};

$user = UserService::resolve();
$user->model->find(['id' => 1]);
 php
class UserService {
    use InstanceMake;

    public function __construct(
        public UserModel $model
    ) {}
};

$user = UserService::resolve();
$user->model->find(['id' => 1]);

// 再次调用时不会重复实例化类
UserService::resolve();

// 指定强制重新实例化类
UserService::resolve(force: true);

 php


use Yesccx\BetterLaravel\Traits\InitializeTraits;

trait RecordLog {

    protected \Illuminate\Log\Logger $logger;

    public function initializeRecordLog()
    {
        $this->logger = app(\Illuminate\Log\Logger::class);
    }

    public function record(string $message)
    {
        $this->logger->info($message);
    }
}

class User {
    use InitializeTraits, RecordLog;
}

$user = new User;
$user->record('test');
 php
class User {
    use InitializeTraits {
        __construct as __traitConstruct;
    }, RecordLog;

    public function __construct()
    {
        $this->__traitConstruct();
    }
}
 php
$foo->withRescue()->getData(1, 1); // return: 1
$foo->withRescue()->getData(1, 0); // return: null
$foo->withRescue(-1)->getData(1, 0); // return: -1
 php
$foo->rescue->getData(1, 0); // return: null
 php
/**
 * dump wrapper
 * PS: 自动对集合做toArray
 *
 * @param mixed $vars
 *
 * @return void
 */
function dumps(mixed ...$vars): void;
 php
/**
 * dd wrapper
 * PS: 自动对集合做toArray
 *
 * @param mixed $vars
 *
 * @return void
 */
function dds(mixed ...$vars): void;
 php
/**
 * 分割字符串数组
 *
 * @param string $str
 * @param string $separator 分割符(默认,)
 *
 * @return array
 */
function explode_str_array(string $str, string $separator = ','): array;
 php
/**
 * 自定义分页
 *
 * @param bool $allowFetchAll 是否允许获取全部
 * @param null|int $perPage 每页数量
 * @param null|int $page 页码
 * @param bool $forceFetchAll 是否强制获取全部
 * @param array $options 扩展选项 @see PaginatorOptions::data
 * @return CustomLengthAwarePaginatorContract
 */
function (
    bool $allowFetchAll = false,
    ?int $perPage = null,
    ?int $page = null,
    bool $forceFetchAll = false,
    array $options = []
): CustomLengthAwarePaginatorContract;
 php
/**
 * 自定义简单分页
 *
 * @param bool $allowFetchAll 是否允许获取全部
 * @param null|int $perPage 每页数量
 * @param null|int $page 页码
 * @param bool $forceFetchAll 是否强制获取全部
 * @param array $options 扩展选项 @see PaginatorOptions::data
 * @return CustomPaginatorContract
 */
function (
    bool $allowFetchAll = false,
    ?int $perPage = null,
    ?int $page = null,
    bool $forceFetchAll = false,
    array $options = []
): CustomPaginatorContract;
 php
$list = \Yesccx\BetterLaravel\Database\CustomLengthAwarePaginator::resolve(items: [], total: 30, perPage: 15, page: 1);
 php
$list = \Yesccx\BetterLaravel\Database\CustomLengthAwarePaginator::toEmpty();
 php
/**
 * 自定义分页
 *
 * @param bool $allowFetchAll 是否允许获取全部
 * @param null|int $perPage 每页数量
 * @param null|int $page 页码
 * @param bool $forceFetchAll 是否强制获取全部
 * @param array $options 扩展选项 @see PaginatorOptions::data
 * @return CustomLengthAwarePaginatorContract
 */
function (
    bool $allowFetchAll = false,
    ?int $perPage = null,
    ?int $page = null,
    bool $forceFetchAll = false,
    array $options = []
): CustomLengthAwarePaginatorContract;
 php
/**
 * 自定义简单分页
 *
 * @param bool $allowFetchAll 是否允许获取全部
 * @param null|int $perPage 每页数量
 * @param null|int $page 页码
 * @param bool $forceFetchAll 是否强制获取全部
 * @param array $options 扩展选项 @see PaginatorOptions::data
 * @return CustomPaginatorContract
 */
function (
    bool $allowFetchAll = false,
    ?int $perPage = null,
    ?int $page = null,
    bool $forceFetchAll = false,
    array $options = []
): CustomPaginatorContract;
 php
/**
 * LIKE查询
 *
 * @param mixed $fields 查询字段
 * @param mixed $keywords 查询值
 * @param int $mode 0-all;1-start;2-end;3-normal
 *
 * @return Builder
 */
function (mixed $fields, mixed $keywords, int $mode = 0): Builder;
 php
/**
 * (when)LIKE查询
 *
 * @param mixed $fields 查询字段
 * @param mixed $keywords 查询值
 * @param int $mode 0-all 1-start 2-end 3-normal
 *
 * @return Builder
 */
function (mixed $fields, mixed $keywords, int $mode = 0): Builder;
 php
/**
 * 查询是否为当日
 *
 * @uses whereThisDay()
 *
 * @param mixed $field 查询字段
 *
 * @return Builder
 */
function (mixed $field): Builder;
 php
/**
 * 查询是否为某日
 *
 * @param mixed $field 查询字段
 * @param mixed $month 日期 2022-01-01
 *
 * @return Builder
 */
function (mixed $field, mixed $day): Builder;
 php
/**
 * 查询是否为本周
 *
 * @param mixed $field 查询字段
 *
 * @return Builder
 */
function (mixed $field): Builder;
 php
/**
 * 查询是否为本月
 *
 * @param mixed $field 查询字段
 *
 * @return Builder
 */
function (mixed $field): Builder;
 php
/**
 * 查询是否为某月
 *
 * @param mixed $field 查询字段
 * @param mixed $month 月份 2022-01
 *
 * @return Builder
 */
function (mixed $field, mixed $month): Builder;
 php
/**
 * 查询是否为本年
 *
 * @param mixed $field 查询字段
 *
 * @return Builder
 */
function (mixed $field): Builder;
 php
/**
 * 查询是否为某年
 *
 * @param mixed $field 查询字段
 * @param mixed $year 年份 2022
 *
 * @return Builder
 */
function (mixed $field, mixed $year): Builder;
 php
/**
 * 查询是否大于指定日期
 *
 * @param mixed $field 查询字段
 * @param mixed $date 日期(默认为当前时间)
 *
 * @return Builder
 */
function (mixed $field, mixed $date = null): Builder;
 php
/**
 * 查询是否大于等于指定日期
 *
 * @param mixed $field 查询字段
 * @param mixed $date 日期(默认为当前时间)
 *
 * @return Builder
 */
function (mixed $field, mixed $date = null): Builder;
 php
/**
 * 查询是否小于指定日期
 *
 * @param mixed $field 查询字段
 * @param mixed $date 日期(默认为当前时间)
 *
 * @return Builder
 */
function (mixed $field, mixed $date = null): Builder;
 php
/**
 * 查询是否小于等于指定日期
 *
 * @param mixed $field 查询字段
 * @param mixed $date 日期(默认为当前时间)
 *
 * @return Builder
 */
function (mixed $field, mixed $date = null): Builder;
 php
/**
 * 查询是在指定日期范围内
 *
 * @param mixed $field 查询字段
 * @param mixed $startDate 开始日期
 * @param mixed $endDate 结束日期
 * @param bool $forceFullDay 是否为强制全天
 *
 * @return Builder
 */
function (string $field, mixed $startDate = null, mixed $endDate = null, bool $forceFullDay = false): Builder;
 php

    // ...

    'http' => [
        'message_body_map' => [
            \Yesccx\BetterLaravel\Http\Supports\ResponseCode::SUCCESS_CODE    => 200,
            \Yesccx\BetterLaravel\Http\Supports\ResponseCode::ERROR_CODE      => 400403,
            \Yesccx\BetterLaravel\Http\Supports\ResponseCode::SUCCESS_MESSAGE => 'success',
            \Yesccx\BetterLaravel\Http\Supports\ResponseCode::ERROR_MESSAGE   => 'error',
        ]
    ]

    // ...
]
 php
/**
 * 响应成功信息
 *
 * @param mixed $message 响应信息
 * @param mixed $data 响应数据
 * @param mixed $code 响应码
 * @param array $headers 响应头
 * @param int $options
 *
 * @return JsonResponse
 */
responseSuccess(
    mixed $message = null,
    mixed $data = [],
    mixed $code = null,
    array $headers = [],
    int $options = 0
): JsonResponse;
 php
/**
 * 响应失败信息
 *
 * @param mixed $message 响应信息
 * @param mixed $code 响应码
 * @param mixed $data 响应数据
 * @param array $headers 响应头
 * @param int $options
 *
 * @return JsonResponse
 */
responseError(
    mixed $message = null,
    mixed $code = null,
    mixed $data = [],
    array $headers = [],
    int $options = 0
): JsonResponse;
 php
/**
 * 响应数据信息
 *
 * @param mixed $data 响应数据
 * @param string|bool $resource 是否使用资源类
 * @param mixed $message 响应信息
 * @param bool $isCollection 是否按集合处理,默认根据响应数据类型判断
 * @param mixed $code 响应码
 * @param array $headers 响应头
 * @param int $options
 *
 * @return JsonResponse
 */
responseData(
    mixed $data = [],
    string|bool $resource = false,
    mixed $message = null,
    bool $isCollection = false,
    mixed $code = null,
    array $headers = [],
    int $options = 0
): JsonResponse;
 php
/**
 * 响应异常信息
 *
 * @param \Throwable $e
 * @param array $options
 *
 * @return JsonResponse
 */
public function responseException(\Throwable $e, array $options = []): JsonResponse;
 php


declare(strict_types = 1);

namespace App\Http\Controllers;

use Yesccx\BetterLaravel\Http\BaseController;
use Illuminate\Http\Request;
use App\Models\User;

final class UserController extends BaseController
{
    public function info(Request $request): \Illuminate\Http\JsonResponse
    {
        $id = $request->get('id', 0);
        if (empty($id)) {
            // 响应失败信息
            return $this->responseError('参数错误');
        }

        $user = User::query()->find($id);
        if (empty($user)) {
            // 响应成功信息
            return $this->responseSuccess('用户暂未注册')
        }

        // 响应数据
        return $this->responseData($user);
    }
}
 php
$this->responseData($user, UserResource::class);
 php
$this->responseData($userList, UserResource::class, isCollection: true);

// 分页查询的结果不需要额外声明isCollection
$userList = User::query()->customPaginate();
$this->responseData($userList, UserResource::class);
 php
$userid = request()->fetch(
    'user_id/d',
    0,
    ['userid' => 123]
);
 php


final class AccountLoginRequest extends BaseRequest
{
    /**
     * Get custom attributes for validator errors.
     *
     * @return array
     */
    public function attributes()
    {
        return [
            'username' => '用户名',
            'password' => '密码',
        ];
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'username' => ['bail', '
 php


use Yesccx\BetterLaravel\Validation\BaseRequest;
use Yesccx\BetterLaravel\Validation\Traits\ValidatorScenes;

final class UserRequest extends BaseRequest
{
    use ValidatorScenes;

    /**
     * 验证场景
     *
     * @return array
     */
    public function scenes(): array
    {
        return [
            'create' => [
                'username', 'password', 'nickname', 'introduction'
            ],
            'update' => [
                'nickname', 'introduction'
            ]
        ];
    }

    /**
     * Get custom attributes for validator errors.
     *
     * @return array
     */
    public function attributes()
    {
        return [
            'username'      => '用户名',
            'password'      => '密码',
            'nickname'      => '昵称',
            'introduction'  => '简介'
        ];
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'username'      => ['bail', '
 php


class UserController
{
    public function create(UserRequest $request)
    {
        // 此处会验证  'username', 'password', 'nickname', 'introduction' 字段
        // Do something ...
    }

    public function update(UserRequest $request)
    {
        // 此处仅验证 'nickname', 'introduction' 字段
        // Do something ...
    }
}
 php
/**
 * 验证场景
 *
 * @return array
 */
public function scenes(): array
{
    return [
        'create' => [
            'username', 'password', 'nickname', 'introduction'
        ],
        'update' => [
            // 此处对 nickname 字段重新声明了验证规则
            'nickname' => ['bail', '
 php
/**
 * @param string $subRequest 子验证类
 *
 * @return void
 */
public function __construct(
    protected string $subRequest
);
 php
/**
 * @param string $subRequest 子验证类
 *
 * @return void
 */
public function __construct(
    protected string $subRequest
);
 php
public function verified(): bool;
 php
public function notVerified(): bool;
 php
public function when(callable $handler, mixed $default): mixed;
 php
# gray environment

GrayEnvironment::instance()->when(
    fn () => 'is gray'
);
// is gray

ProdEnvironment::instance()->when(
    fn () => 'is prod'
);
// null

GrayEnvironment::instance()->when(
    fn () => 'is gray',
    fn () => 'is not gray'
);
// is gray
 php
public function whenNot(callable $handler, mixed $default): mixed;
 php
public function wrapStr(string $value): string;