PHP code example of thefair / thefairlib

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

    

thefair / thefairlib example snippets


public function getTest()
{
    $uid = input('uid');
    $name = input('name');
    $fields = input('fields', []);
    return $this->showResult([
        $uid,
        $fields,
        $name,
    ]);
}



declare(strict_types=1);

namespace App\Request\V2\Test;

use App\Request\BaseRequest;

class GetTest extends BaseRequest
{

    /**
     * Get the validation rules that apply to the request.
     */
    public function rules(): array
    {
        return [
            'uid' => ' ':attribute 不能为空',
            'uid.integer' => ':attribute 必须为整型',
            'fields.array' => ':attribute 必须为数组',
            'ignore_cache.boolean' => ':attribute 必须为 true 或 false',
        ];
    }
}


getCookie('xxx');
getCookies();
getCookies();
setCookies(new \Hyperf\HttpMessage\Cookie\Cookie('xxx', 'xxx', time() + 86400, '/', $domain));



declare (strict_types=1);
namespace App\Model\User;

use TheFairLib\Model\DataModel;
/**
 * @property int $uid 用户id,用于做sharding
 * @property string $username 用户名
 * @property string $country_code 国家编码
 * @property string $country 注册国家
 * @property int $nationality 国籍
 * @property string $nick 昵称
 * @property string $sex 用户性别
 * @property string $mobile 用户手机号(加密)
 * @property string $password 用户密码
 * @property string $avatar 头像地址
 * @property string $state 用户状态
 * @property string $source 注册来源
 * @property string $app_source 注册应用来源
 * @property string $self_desc 自我描述
 * @property string $auth_desc 认证描述
 * @property string $geek_desc 达人描述
 * @property string $salt 加密salt
 * @property string $last_visit_time 最后访问时间
 * @property string $last_visit_ip 
 * @property string $reg_ip 
 * @property string $ctime 创建时间
 * @property string $utime 更新时间
 */
class UserInfo extends DataModel
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'user_info';
    /**
     * The connection name for the model.
     *
     * @var string
     */
    protected $connection = 'xxx_user';
    /**
     * sharding num
     *
     * @var int
     */
    protected $shardingNum = 20;
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['uid', 'username', 'country_code', 'country', 'nationality', 'nick', 'sex', 'mobile', 'password', 'avatar', 'state', 'source', 'app_source', 'self_desc', 'auth_desc', 'geek_desc', 'salt', 'last_visit_time', 'last_visit_ip', 'reg_ip', 'ctime', 'utime'];
    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = ['uid' => 'integer', 'nationality' => 'integer'];
}

public function getUserDevice($uid, $deviceId)
{
    return (array)self::shardingId($uid)->where([
        'uid' => $uid,
        'device_id' => $deviceId,
    ])->first();
}

UserInfo::shardingId($uid)->where([
    'uid' => $uid,
    'device_id' => $deviceId,
])->first();

UserInfo::query()->paginate(3)])

/**
 * 原生 sql 测试
 *
 * @return array
 * @throws ConnectionException
 */
public function rawSql()
{
    $uid = "1 or 1=1";
    return $this->db()->select("select * from xxx_user_info_0 where uid = {$uid}");
}

/**
 * 原生 sql 测试
 *
 * @return array
 * @throws ConnectionException
 */
public function rawSql()
{
    $nick = "1 or 1=1";
    return $this->db()->select("select * from xxx_user_info_0 where nick = $nick");
}

TheFairLib\Library\Cache\Redis::getContainer('pool_name')->set();
TheFairLib\Library\Cache\Redis::getContainer('pool_name')->get();

getItemListByPageFromCache(self::REDIS_POOL, $name, $lastItemId, 'asc', $itemPerPage, true);

//页码 
listItemFromCache(self::REDIS_POOL, $name, 1,'desc', $itemPerPage, true);

@CacheSet(prefix="str:xxxx", value="#{xxx}", ttl=5, group="pool_name")

throw new ServiceException('用户已经注册', ['uid' => $checkUid, 'third_party_uid' => hideStr($thirdPartyUid), 'mobile' => hideStr($mobile)]);

{
    "code": 40001,
    "message": {
        "text": "用户已经注册",
        "action": "toast"
    },
    "result": {
        "uid": 1111,
        "third_party_uid": "933**************************8c1",
        "mobile": "186*****263",
        "exception": "App\\Exception\\ServiceException"
    }
}

throw new BusinessException(ErrorCode::CODE_RATE_LIMIT, ['host' => getServerLocalIp()]);

{
    "code": 50003,
    "message": {
        "text": "192*******.43 服务器超时, 请稍后再试",
        "action": "toast"
    },
    "result": {
        "exception": "App\\Exception\\BusinessException"
    }
}

throw new EmptyException('数据为空', ['uid' => 1]);

{
    "code": 40001,
    "message": {
        "text": "数据为空",
        "action": "toast"
    },
    "result": {
        "uid": 1,
        "exception": "App\\Exception\\EmptyException"
    }
}

$data = \TheFairLib\Service\JsonRpc\RpcClient\Client::Instance('xxx_service')->call('/v2/test/get_test', [

]);

\TheFairLib\Library\Search\Elastic::getContainer()->get([
    'index' => 'xxx',
    'type' => 'xxx',
    'id' => 1,
]);



declare(strict_types=1);

return [
     'consumers' => [
        [
            'name' => 'v2/test',
            'service' => '',
            'protocol' => 'jsonrpc-tcp-length-check',
            'load_balancer' => 'random',
            'nodes' => [
                [
                    'host' => '192.168.0.249',
                    'port' => 2301,
                ],
            ],
            'app_key' => 'xxx',
            'app_secret' => 'xxx1111',
            // 配置项,会影响到 Packer 和 Transporter
            'options' => [
                'connect_timeout' => 5.0,
                'recv_timeout' => 5.0,
                'settings' => [
                    // 根据协议不同,区分配置
                    'open_length_check' => true,
                    'package_length_type' => 'N',
                    'package_length_offset' => 0,
                    'package_body_offset' => 4,
                    'package_max_length' => 1024 * 1024 * 2,
                ],
                // 当使用 JsonRpcPoolTransporter 时会用到以下配置
                'pool' => [
                    'min_connections' => 1,
                    'max_connections' => 32,
                    'connect_timeout' => 10.0,
                    'wait_timeout' => 3.0,
                    'heartbeat' => -1,
                    'max_idle_time' => 60.0,
                ],
            ],
        ],
    ],
];



function smart(string $method, array $params = [], int $ttl = 0, string $poolName = 'default'): array {}

RpcClient::get('content_service')->smart('v1/test/get_test', [], 1000, 'user_info');

   'force_update' => [
       '/v1/test/test',
   ],
   
shell
php bin/hyperf.php request
shell
php bin/hyperf.php gen:dataModel user_info
ini
LOG_DIR=/home/xxx/logs/www/  # 日志保存路径
CLOSE_LOG=0 # 1为关闭日志,0为正常
LOG_MAX_FILES_DAY=30 # 日志保存天数

/**
 * @Doc(name="测试方法", tag={"user", "api"})
 *
 * @return array
 */
// ...  
shell
composer analyse