MongoDB之PHP的使用(GridFs)

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

一个简单上传例子:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
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"

com.atlassian.confluence.content.render.xhtml.XhtmlException: Missing required attribute: {http://atlassian.com/resource/identifier}value

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

附上简单的调用:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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/