Categories
php

php 自定义类替换第三方包同名文件

修改自动加载规则

  1. 调整composer.json:如果必须的话,你可以调整composer.json中的autoload部分,使得你的类优先于第三方包被加载。但是,这种方法较为复杂,并且可能导致难以预测的行为。json深色版本{ "autoload": { "psr-4": { "Vendor\\Package\\": "path/to/your/classes" } } }
  2. 重新dump自动加载器:当你改变了自动加载规则后,需要运行composer dump-autoload来更新自动加载器。
Categories
php

laravel wechat

用户登录流程

小程序调用 wx.login 后获得 code ,调用 laravel-wechat 的login 接口

https://depscreen.studentvision.cn/api/wechat/mini/login

返回 用户个人信息 openid accessToken 等

{
	"error_code": 0,
	"data": {
		"access_token": "bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczovL2RlcHNjcmVlbi5zdHVkZW50dmlzaW9uLmNuL2FwaS93ZWNoYXQvbWluaS9sb2dpbiIsImlhdCI6MTczMzk4NzMzMCwiZXhwIjoxNzMzOTkwOTMwLCJuYmYiOjE3MzM5ODczMzAsImp0aSI6IkFUTTloR1dvU1VuNjlaWWgiLCJzdWIiOiIxIiwicHJ2IjoiNDI1MTRkODBlZTM4NWRhODRjYTM4YWY0NTgyZThmNTRiYjRjZmIzOSJ9.qLXirUDL8GJjkg3LS47_J1LEpdA5j02VgyfUrt6RrpY",
		"expires_in": 3600,
		"wechat_user": {
			"id": 1,
			"app_id": "wx621e0fe15a370854",
			"user_id": "0",
			"openid": "oLG3w68wIQoTn5BwLOVyREIMtiFM",
			"nickname": null,
			"avatar": null,
			"gender": "0",
			"country": null,
			"province": null,
			"city": null,
			"subscribed_at": null,
			"created_at": "2024-12-11T04:15:17.997000Z",
			"updated_at": "2024-12-11T04:15:17.997000Z",
			"gender_readable": null
		}
	}
}

之后的每个请求都要带上 该jwt access token 作为通信票据以保证安全

Accept:application/json
Content-Type:application/json
Authorization:bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczovL2RlcHNjcmVlbi5zdHVkZW50dmlzaW9uLmNuL2FwaS93ZWNoYXQvbWluaS9sb2dpbiIsImlhdCI6MTczMzk4NzMzMCwiZXhwIjoxNzMzOTkwOTMwLCJuYmYiOjE3MzM5ODczMzAsImp0aSI6IkFUTTloR1dvU1VuNjlaWWgiLCJzdWIiOiIxIiwicHJ2IjoiNDI1MTRkODBlZTM4NWRhODRjYTM4YWY0NTgyZThmNTRiYjRjZmIzOSJ9.qLXirUDL8GJjkg3LS47_J1LEpdA5j02VgyfUrt6RrpY

controller 增加一个middleware 作为checking

Route::middleware('auth:mini')

具体实现类是
这个作为jwt入口
 Tymon\JWTAuth\Providers\LaravelServiceProvider::class,
 php artisan  jwt:secret

该命令可以重新生成jwt 私钥

Categories
php

laravel 默认 token 校验

调用的是TokenGuard 这个类

数据库user 表有 字段名为 api_token 的校验 用来存放token

用户登录后会获取该token 之后所有请求 都要带上该token

该token没有超时机制 每次获取user个人信息需要根据token查一次数据库 比jwttoken 性能要差

Categories
php

laravel jwt

为api 调用提供身份校验功能

docs https://jwt-auth.readthedocs.io/

install

composer require tymon/jwt-auth

Add the service provider to the providers array in the config/app.php config file as follows:

'providers' => [

    ...

    Tymon\JWTAuth\Providers\LaravelServiceProvider::class,
]

Run the following command to publish the package config file:

php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"

Generate secret key

This will update your .env file with something like JWT_SECRET=XXX

php artisan jwt:secret

该包 修改laravel api 路径下默认的 token校验方式 把token改为JWT token

其实生成流程和校验流程和之前没变化

login 通过用户账号密码 作为 credentials 然后去数据库获取用户信息 该用户信息会生成JWT token 放在laravel 默认缓存管理器

后续请求 在请求头带上 Authorazation : bear $token

通过auth:api 中间件校验

Categories
php

php guzzle 发送http 请求

docs https://docs.guzzlephp.org/

install

composer require guzzlehttp/guzzle

sync get

$client = new \GuzzleHttp\Client();
$response = $client->request('GET', 'https://api.github.com/repos/guzzle/guzzle');

echo $response->getStatusCode(); // 200
echo $response->getHeaderLine('content-type'); // 'application/json; charset=utf8'
echo $response->getBody(); // '{"id": 1420053, "name": "guzzle", ...}'

async get

$request = new \GuzzleHttp\Psr7\Request('GET', 'http://httpbin.org');
$promise = $client->sendAsync($request)->then(function ($response) {
    echo 'I completed! ' . $response->getBody();
});

$promise->wait();

post

$client = new \GuzzleHttp\Client();
$response = $client->request('POST', 'https://api.github.com/repos/guzzle/guzzle',
 [
   'headers' => [
        'User-Agent' => 'testing/1.0',
        'Accept'     => 'application/json',
        'X-Foo'      => ['Bar', 'Baz']
    ],
    //'query' => ['foo' => 'bar']  //query params
    //'body' => 'foo'   // plain string BODY
    /* 'form_params' => [   //  application/x-www-form-urlencoded
        'foo' => 'bar',
        'baz' => ['hi', 'there!']
    ]*/
    //'json' => ['foo' => 'bar']]  //json body  application/json

    /*'multipart' => [    multipart    multipart/form-data
        [
            'name'     => 'foo',
            'contents' => 'data',
            'headers'  => ['X-Baz' => 'bar']
        ],
        [
            'name'     => 'baz',
            'contents' => Psr7\Utils::tryFopen('/path/to/file', 'r')
        ],
        [
            'name'     => 'qux',
            'contents' => Psr7\Utils::tryFopen('/path/to/file', 'r'),
            'filename' => 'custom_filename.txt'
        ],
    ]*/


 ],
 
);

echo $response->getStatusCode(); // 200
echo $response->getHeaderLine('content-type'); // 'application/json; charset=utf8'
echo $response->getBody(); // '{"id": 1420053, "name": "guzzle", ...}'
Categories
php

php curl 发送http 请求

php.ini 开通 curl模块

post

 $url = "http://beiko.robinluo.top/api/student";


        $jsonStr = json_encode(array(
                'name' =>$name,
                'sex' => $sex,
                'person_no' => $person_no,
                'idcard' => $idcard,
                'organization_no' => $organization_no
            )
        );
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json; charset=utf-8',
                'Content-Length: ' . strlen($jsonStr),
            )
        );
        $response = curl_exec($ch);
        curl_close($ch);

get

function curl($url, $data = [],$header = [])
{
    // 处理get数据
    if (!empty($data)) {
        $url = $url . '?' . http_build_query($data);
    }

    // dd($url);

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HEADER, false);
    curl_setopt($curl, CURLOPT_HTTPHEADER,$header);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);//这个是重点。
    $result = curl_exec($curl);
    curl_close($curl);
    return $result;
}
Categories
php

thinkphp 启动命令

php -S localhost:8080 -t public

指定当前public目录位对外目录

Categories
php

laravel 一对多

class OctopusRecord extends Model
{
    use SoftDeletes;
    use HasFactory;
    protected $connection = "beiko_mysql";
    protected $table = 'octopus_records';

    //所有字段一定要满足 小写下划线模式
    public function triage_tags()
    {
        return $this->hasMany(OctopusRecordTriageTag::class,"octopus_record_id");
    }

}
$form->tab("分诊信息",function (Form $subform) {
            $subform->hasMany('triage_tags', "分诊标签", function (Form\NestedForm $nestedForm) {
                $nestedForm->hidden('id');
                $nestedForm->select('name', "标签")->options(TriageTag::all()->pluck('name', 'name'));
                //$nestedForm->text('name', "标签");
            });
            //->distinctFields(["name"]);
                //->useTable();
            //->useTab();;
            //$form->multipleSelect('triage_tags', "分诊标签")->options([0=>"无效",1=>"有效"]);
            //->options(TriageTag::all()->pluck('name', 'name'));

            $subform->textarea('conclusion', __('Conclusion'));
        });
Categories
php

laravel log

use Illuminate\Support\Facades\Log;

Log::info("triageTeam" . json_encode($triageTeam));
Log::info("schools" . json_encode($triageTeam->schools()));

强制使用dd($variable)能在页面打印变量 很好用

Categories
php

php-fpm

php-fpm 是以守护进程形式执行php进程 以便下游服务器发送cgi通信数据过来 然后通过标准输出流返回网页数据到 cgi服务器

具体关键配置

进程owner 用户(权限相关)

user = www-data
group = www-data

listen.acl_users = apache,nginx,www-data
 //允许访问的用户

子进程数量限制 (性能相关)

监听方式(unix file socket 或者 tcp ip socket)(注意unix:socket 方式需设定该文件读写权限)

listen = /run/php-fpm/www.sock
listen.owner = nobody
listen.group = nobody
listen.mode = 0660


listen = 127.0.0.1:6000
listen.allowed_clients = 127.0.0.1

debug 配置