php常用扩展

发布时间 2024-01-11 17:01:44作者: xirang熙攘

php通用扩展

图片处理扩展

https://packagist.org/packages/intervention/image
https://image.intervention.io/v2/introduction/installation
支持 Laravel 集成的图像处理和操作库

//安装
composer require intervention/image

代码示例

// 打开图像文件
$img = Image::make('public/foo.jpg');
//可以直接传入request请求的文件对象
$img = Image::make($request()->file('file'));
//或者传入 使用 response file 移动后返回的文件
$file=$request()->file('file')->move('路径','名字');
$img = Image::make($file);
// 调整图像实例的大小
$img->resize(320, 240);
// 自适应高度
$img->resize(300, null, function ($constraint) {
        $constraint->aspectRatio();
    });
// 插入水印
$img->insert('public/watermark.png');
// 以所需格式保存图像 第二个参数为质量可选  可选第三个参数修改文件格式
$img->save('public/bar.jpg',100);

使用自动加载类来实现

// 使用自动加载
require 'vendor/autoload.php';
//导入干预图像管理器类
use Intervention\Image\ImageManager;
//使用受青睐的驱动程序创建映像管理器实例
$manager = new ImageManager(['driver' => 'imagick']);
//以最终创建图像实例
$image = $manager->make('public/foo.jpg')->resize(300, 200);

使用静态

// 使用自动加载
require 'vendor/autoload.php';
//导入干预图像管理器类
use Intervention\Image\ImageManagerStatic as Image;
//使用喜爱的图像驱动程序进行配置(默认为gd)
Image::configure(['driver' => 'imagick']);
//你已经准备好出发了。。。
$image = Image::make('public/foo.jpg')->resize(300, 200);

集成成到laravel中去

config/app.php中添加

// $providers数组中添加
Intervention\Image\ImageServiceProvider::class
//$aliases 数组中添加
'Image' => Intervention\Image\Facades\Image::class

默认情况下,Intervention Image 使用 PHP 的 GD 库扩展来处理所有图像。如果您想切换到 Imagick,您可以通过运行以下 artisan 命令之一将配置文件拉入您的应用程序。

在laralvel中发布配置

php artisan vendor:publish --provider="Intervention\Image\ImageServiceProviderLaravelRecent"
# laravel版本<=4的时候用这个
php artisan config:publish intervention/image

markdown处理

https://packagist.org/explore/?query=markdown
可以把markdown的内容转化为html

es扩展 (elasticsearch )

官网: https://www.elastic.co/guide/en/elasticsearch/client/php-api/current/index.html

文档:
https://www.elastic.co/guide/en/elasticsearch/client/php-api/current/getting-started-php.html

软件下载: https://elasticsearch.cn/download/

扩展安装
composer require elasticsearch/elasticsearch

ElasticSearch重置密码步骤(忘记密码的情况)

1.停止Elasticsearch服务
2.编辑elasticsearch.yml文件,设置以下两项为false;
	xpack.security.enabled: false
	xpack.security.transport.ssl.enabled: false
3.重启es服务,删除.security-7索引
	curl -XDELETE -u elastic:changeme http://localhost:9200/.security-7
3.关闭ES服务设置以下两项为true;
	xpack.security.enabled: true
	xpack.security.transport.ssl.enabled: true
4.重启es服务,进入es的bin目录下
	./elasticsearch-setup-passwords interactive
	依次设置每个账号密码即可

获取密码:
进入es安装目录的bin文件中执行一下命令会返回最新的密码
命令 : elasticsearch-reset-password -u elastic
默认用户名: elastic
密码: QhW4NJSQGzP13o2kVI6o
修改密码的其他命令
https://devpress.csdn.net/cloud-native/65195642aae4e179c0b77cc4.html

开启各种安全验证后需要ssl证书才能正常登录

xpack.security.enabled: true
xpack.security.enrollment.enabled: true
xpack.security.http.ssl:
  enabled: true
  keystore.path: certs/http.p12
xpack.security.transport.ssl:
  enabled: true
  verification_mode: certificate
  keystore.path: certs/transport.p12
  truststore.path: certs/transport.p12

证书位置 config\certs\http_ca.crt

config/es.php文件配置

return [
    'host'=>['https://127.0.0.1:9200'],
    'user'=>'elastic',
    'pwd'=>'VX_IuVXQ6_WcfmBO8Mxc',
];
//初始化
use Elastic\Elasticsearch\ClientBuilder;
use Elastic\Elasticsearch\Exception\ClientResponseException;
use Elastic\Elasticsearch\Exception\ServerResponseException;
$client = ClientBuilder::create()
    ->setHosts(config('es.host'))
    ->setBasicAuthentication(config('es.user'), config('es.pwd'))
    ->setCABundle('cacrt/http_ca.crt')
    ->build();

分词器要下载对应的版本
https://github.com/medcl/elasticsearch-analysis-ik
下载地址
https://github.com/medcl/elasticsearch-analysis-ik/releases

下载后解压到 plugins/ik 目录下面 重启 es即可

//创建映射
curl -XPOST http://localhost:9200/index/_mapping -H 'Content-Type:application/json' -d'
{
        "properties": {
            "content": {
                "type": "text",
                "analyzer": "ik_max_word",
                "search_analyzer": "ik_smart"
            }
        }
}'
案例 增删查改
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Elastic\Elasticsearch\ClientBuilder;
use Elastic\Elasticsearch\Exception\ClientResponseException;
use Elastic\Elasticsearch\Exception\ServerResponseException;
use Illuminate\Support\Facades\DB;


class MyesController extends Controller
{
    protected $client;

    public function __construct()
    {
        //初始化es
        $this->client = $this->_init_es();
    }

    public function index()
    {
        // 创建索引
        // $res = $this->_create_index();
        //   dd($res);
        // $item = DB::table('article')->first();
        // dd($item);
        // $article_list = DB::table('article')->where('id', '<', 300)->get()->toArray();
        // foreach ($article_list as $item) {
        //     $this->insert_update($item);
        // }

        //把数据写入搜索引擎
        // $res=$this->insert_update($item);
        // dd($res);
        //删除文档
        // $this->del_doc();
        //删除索引
        $this->del_index();
        //全文搜索
        // $res = $this->dosearch('C');
        // echo "<pre>";
        // print_r($res);
    }

      //初始化es
    private function _init_es()
    {
        $es_config = [
            'host' => ['https://127.0.0.1:9200'],
            'user' => 'elastic',
            'pwd' => 'QhW4NJSQGzP13o2kVI6o',
            'cacrt' => base_path() . '\private\certs\http_ca.crt',
        ];

        $client = ClientBuilder::create()
            ->setHosts($es_config['host'])
            ->setBasicAuthentication($es_config['user'], $es_config['pwd'])
            ->setCABundle($es_config['cacrt'])
            ->build();
        return $client;
    }
    //创建索引
    private function _create_index()
    {
        $params = [
            'index' => 'article',  //索引的名称(相当于mysql中的表明)
            'body' => [
                'settings' => [
                    'number_of_shards' => 5, //设置数据的分片数,默认为5
                    'number_of_replicas' => 0, // 数据的备份数(如果只有一台机器,设置为0)
                ],
                'mappings' => [
                    'properties' => [
                        'id' => [
                            'type' => 'integer'
                        ],
                        'cid' => [
                            'type' => 'integer'
                        ],
                        'title' => [
                            'type' => 'text',  // text类型,做模糊搜索用
                            "analyzer" => "ik_max_word",   //较细粒度分词,写入数据用
                            "search_analyzer" => "ik_smart", // 较粗粒度分词,查询数据用
                        ],
                        'descs' => [
                            'type' => 'text',
                        ],
                        'author' => [
                            'type' => 'keyword',  // keyword类型,做精确搜索用
                        ],
                    ],
                ],
            ],
        ];
        $res = $this->client->indices()->create($params);
        // 注意:索引不存在,就创建它。如果已存在,会报异常
        return $res;
    }

  
    //写入文档数据(_doc 相当于 mysql表中的一条记录)
    private function insert_update($item)
    {
        $params = [
            'index' => 'article',
            'type' => '_doc',
            'id' => $item->id,
            'body' => [
                'id' => $item->id,
                'cid' => $item->cid,
                'title' => $item->title,
                'descs' => $item->descs,
                'author' => $item->author,
            ]
        ];
        $res = $this->client->index($params);
        // 注意:该文档不存在就创建一个,存在的话,就更新它
        return  $res;
    }
    //全文搜索

    private function dosearch($keyword)
    {    
        $eswhere = [];
        $eswhere['bool']['must'][] = ['match' => ['title' => $keyword]];
        $eswhere['bool']['must'][] = ['match' => ['descs' => $keyword]];
        $esorder = ['id' => 'DESC'];
        $where = [
             		// size和from组合可以用于分页
            'size' => 10, //  取10条数据
            'from' => 0, // 从第几条开始取
            'index' => 'article',  // 从哪个索引中查
            'type' => '_doc',
            'body' => [
                'query' => $eswhere, //查询条件
                // 'sort' => $esorder,   //排序条件 ,加上以后,_score 没有值
                //高亮显示
                'highlight' => [
                    'fields' => [
                        'title' => [
                            'pre_tags' => ['<span style="color:red">'],
                            'post_tags' => ['</span>']
                        ],
                        'descs' => [
                            'pre_tags' => ['<span style="color:red">'],
                            'post_tags' => ['</span>']
                        ],
                    ],
                ],
            ]
        ];
        $results = $this->client->search($where);
        // $milliseconds = $results['took'];
        // $maxScore     = $results['hits']['max_score'];
        // $score = $results['hits']['hits'][0]['_score'];
        // $doc   = $results['hits']['hits'][0]['_source'];
        return  $results->asArray();
    }
    //删除文档
    private function del_doc()
    {
        for ($i = 1; $i < 1000; $i++) {
            $this->client->delete(['index' => 'article', 'id' => $i]);
        }
        // 注意:如果该文档已经删除了,重复删除会报异常
        exit('删除完成');
    }
    //删除索引
    private function del_index()
    {
        $this->client->indices()->delete(['index' => 'article']);
        // 注意:如果该索引已经删除了,重复删除会报异常
    }
}

HTTP Requests for PHP

安装

文档 https://requests.ryanmccue.info/download/
composer require rmccue/requests

使用案例

$response = WpOrg\Requests\Requests::get('https://api.github.com/events');

var_dump($response->body);
// string(42865) "[{"id":"15624773365","type":"PushEvent","actor":{...
//post请求
$response = WpOrg\Requests\Requests::post('https://httpbin.org/post');

//设置请求头
$url = 'https://api.github.com/some/endpoint';
$headers = array('Content-Type' => 'application/json');
$data = array('some' => 'data');
$response = WpOrg\Requests\Requests::post($url, $headers, json_encode($data));