MongoDB之PHP的使用(GridFs)

摘要:最近在做一个文档管理系统,使用MongoDB存储二进制数据,也遇到了很多坑,在这里分享一下

PS:用的新版的MongoDB

一:第一种方法,直接调Driver的方式:

一个简单上传例子:

classMongoPHP

{

    private $_db='publicfiles';

    private $manager=null;

    public function__construct($config= ['host'=>'localhost','port'=>27017])

    {

        $server=sprintf("mongodb://%s:%s",$config['host'],$config['port']);

        $this->manager=newMongoDB\Driver\Manager($server);

    }

    /**

    * insert插入

    *@param$arr

    *@returnmixed

    */

    public functioninsertDb ($table='',$arr= []) {

        $bulk=newMongoDB\Driver\BulkWrite;

        $_id=newMongoDB\BSON\ObjectID;

        $arr['_id'] =$_id;

        $_id=$bulk->insert($arr);

        $writeConcern=newMongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY,1000);

        $result=$this->manager->executeBulkWrite($this->_db.'.'.$table,$bulk,$writeConcern);

        return['_id'=>$_id,'statsu'=>$result->getWriteConcernError()];

    }

}

$mongo=newMongoPHP();

$data= [

    'fileName'=>'1',

    'fileTyple'=>'doxs',

    'fileSize'=>'1024',

    'fileContent'=>'',

    'isGenerateJpg'=>1,

    'generatePage'=>2

];

$mongo->insertDb('publicfiles');

这样处理显然是没有问题的,但是我在使用GridFs的时候,发现新版的已经找不到对它的使用了,找了很多资料都不符合我的需求.

今天突然在PHP官网看到了一个关于MongDB的类库。。。好把,瞬间感觉泪崩,附上连接http://php.net/manual/en/mongodb.tutorial.library.php

使用composer安装好就直接可以用了(很简单),附上我的安装版本:"mongodb/mongodb":"^1.2"


自己写的一个简单的PHP框架

附上简单的调用:

require './vendor/autoload.php';//首先引入

$clent=newMongoDB\Client("mongodb://localhost:27017");//连接数据库

1.添加数据

$recordArray = [];//随便一个数组

$contentCollection=$clent->publicfiles->fileContent;//database+collection

$contentResult=$contentCollection->insertOne($recordArray);

$contentResult->isAcknowledged()//返回bool值

$contentResult->getInsertedId()//返回插入ID,一个对象,如果需要将其存入mysql可以strval()转成字符串

2.GridFs存储文件

$gridFsCollection=$clent->publicfiles->selectGridFSBucket();//这里只指定了databases,collection按照默认的来就行

$file=fopen($fileName,'rb');

$gridFsResult=$gridFsCollection->uploadFromStream($data['fileName'],$file);//返回fs.file中的_id

3.GridFs获取文件二进制流

$data_id=Object("231223er23r4rr223r233r");

$gridFsCollection=$clent->publicfiles->selectGridFSBucket();

$stream=$gridFsCollection->openDownloadStream($data_id);

$contentString=stream_get_contents($stream);//二进制流数据

这样子就完美处理了,无论你用什么框架还是自己写原生的框架都可以

这里附上mongodb php库的说明文档https://docs.mongodb.com/php-library/current/tutorial/gridfs/


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章