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/


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