1、安装

  运行

php composer.phar require --prefer-dist yiisoft/yii2-mongodb

or add

"yiisoft/yii2-mongodb": "~2.0.0"

to the require section of your composer.json.

2、配置

main.php里加入

return [ //.... 'components' => [ 'mongodb' => [ 'class' => '\yii\mongodb\Connection', 'dsn' => 'mongodb://developer:password@localhost:27017/mydatabase', ], ], ];

例如:

'mongodb' => [
'class' => '\yii\mongodb\Connection',
'dsn' => 'mongodb://127.0.0.1:27017/local',
],

3、实体类编写

ChatMsg.php

<?php

namespace common\models;

use Yii;
use yii\behaviors\TimestampBehavior;

class ChatMsg extends \yii\mongodb\file\ActiveRecord
{
/*public static function find()
{
return parent::find()->where(['deleted' => false]);
}*/

//public static function find()
//{
// use CustomerQuery instead of the default ActiveQuery
//return new CustomerQuery(get_called_class());
//}
public function attributes()
{
return array_merge(
parent::attributes(),
[
'content',
'messageId',
'from',
'to',
'conversationId',
'timestamp',
'imageUrl',
'imageSize',
'imageWidth',
'imageHeight',
'type']
);
}

}

// Use andWhere()/orWhere() to apply the default condition
// SELECT FROM customer WHERE `deleted`=:deleted AND age>30
//$customers = ChatMsg::find()->andWhere('age>30')->all();

// Use where() to ignore the default condition
// SELECT FROM customer WHERE age>30
//$customers = ChatMsg::find()->where('age>30')->all();

4、控制器编写

<?php
namespace frontend\controllers;
use common\helper\MyHttpBasicAuth;
use common\helper\UtilHelper;
use common\models\ChatMsg;
use yii\filters\Cors;
use yii\helpers\ArrayHelper;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\filters\auth\HttpBasicAuth;
use yii\caching\DbDependency;
use yii\mongodb\Query;

class ChatController extends Controller
{
public $enableCsrfValidation = false;
public function behaviors()
{

$behaviors = parent::behaviors();
$behaviors['authenticator'] = [
'class' => MyHttpBasicAuth::className(),
'except'=>['createmessage', 'getmessages'],
];

$behaviors = ArrayHelper::merge([
[
'class' => Cors::className(),
],
], $behaviors);

return $behaviors;
}

public function actionGetmessages() {
$query = new Query;
// compose the query
$query->select(['content', 'messageId','from','to','conversationId','timestamp', 'imageUrl','imageSize','imageWidth','imageHeight','type'])
->from('aaa.files')
->limit(10);
// execute the query
//$rows = $query->all();
$rows = ChatMsg::find()->asArray()->all();
$rt['e'] = 0;
$rt['datas'] = $rows;
return json_encode($rt);

}

public function actionCreatemessage() {
$request = \Yii::$app->request;
if (!$request->isPost) {
return json_encode(['e'=>1001, 'm'=>'错误的请求类型']);
}

if (!isset($_POST['data'])) {
return json_encode(['e'=>1002, 'm'=>'缺少必要参数']);
}

$rowJson = $_POST['data'];
$reqData = json_decode($rowJson, true);

$messageId = 0;
if (isset($reqData['messageid'])) {
$messageId = $reqData['messageid'];
}
$from = 0;
if (isset($reqData['from'])) {
$from = intval($reqData['from']);
}
$to = 0;
if (isset($reqData['to'])) {
$to = intval($reqData['to']);
}
$imageWidth = 0;
if (isset($reqData['imagewidth'])) {
$imageWidth = intval($reqData['imagewidth']);
}
$imageHeight = 0;
if (isset($reqData['imageheight'])) {
$imageHeight = intval($reqData['imageheight']);
}
$imageSize = 0;
if (isset($reqData['imagesize'])) {
$imageSize = intval($reqData['imagesize']);
}

$conversationId = 0;
if (isset($reqData['conversationid'])) {
$conversationId = $reqData['conversationid'];
}
$timestamp = 0;
if (isset($reqData['timestamp'])) {
$timestamp = intval($reqData['timestamp']);
}
$type = 0;
if (isset($reqData['type'])) {
$type = intval($reqData['type']);
}
$content = '';
if (isset($reqData['content'])) {
$content = $reqData['content'];
}
$imageUrl = '';
if (isset($reqData['imageurl'])) {
$imageUrl = $reqData['imageurl'];
}

$msg = new ChatMsg();
$msg->imageUrl = $imageUrl;
$msg->imageWidth = $imageWidth;
$msg->imageHeight = $imageHeight;
$msg->imageSize = $imageSize;
$msg->content = $content;
$msg->type = $type;
$msg->timestamp = $timestamp;
$msg->conversationId = $conversationId;
$msg->to = $to;
$msg->from = $from;
$msg->messageId = $messageId;

$msg->save();
if (!$msg->save()) {
return json_encode(['e'=>1004]);
}

return json_encode(['e'=>0, 'm'=>'添加成功!']);

}
}

php yii框架使用MongoDb的更多相关文章

  1. Yii2框架与MongoDB拓展、Redis拓展的安装流程

    @author 周煦辰 2016-03-21 这段时间新上了一个项目,使用的是Yii2框架.这里记录一下Yii2框架.Yii2-Mongo拓展.Yii2-Redis拓展等的安装流程.因为使用的系统是W ...

  2. YII框架源码分析(百度PHP大牛创作-原版-无广告无水印)

           YII 框架源码分析    百度联盟事业部——黄银锋 目 录 1. 引言 3 1.1.Yii 简介 3 1.2.本文内容与结构 3 2.组件化与模块化 4 2.1.框架加载和运行流程 4 ...

  3. yii框架安装心得

    最近在学习yii框架, 现在将遇到的一些问题和解决方法写出来与大家分享. yii框架的安装: 下载yii框架之后, 打开文件运行init.bat文件, 如果闪退就打开php的扩展(php_openss ...

  4. Yii框架 400 错误

    YII  400错误 在YII框架中400错误是csrf校验失败的意思 csrf是什么? CSRF(Cross-site request forgery跨站请求伪造,也被称为"One Cli ...

  5. Yii框架CURD方法

    在YII框架中,CURD有2种方式: 1.AR模式:2. DAO模式 AR模式下 查全部   MODEL  $model->find()->asArray()->all()查单 个  ...

  6. Yaf(Yet Another Framework)用户手册 yii框架手册

    地址:http://www.laruence.com/manual/ yaf框架手册:http://pan.baidu.com/s/1bnHFPHd yii框架手册:http://pan.baidu. ...

  7. yii框架的理解

    Yii Framework是一个基于组件.用于开发大型 Web 应用的高性能 PHP 框架.Yii提供了今日Web 2.0应用开发所需要的几乎一切功能.Yii是最有效率的PHP框架之一. yii框架里 ...

  8. 使用Yii框架完整搭建网站流程入门

    下载地址: http://www.yiiframework.com/ http://www.yiichina.com/ 由美籍华人薛强研究而出, Yii 这个名字(读作易(Yee))代表 简单(eas ...

  9. Yii框架(Yii Framework)部署

    一.下载Yii 在部署yii框架之前首先要搭建好php环境,这里就不说搭建环境的问题了(这里已经部署好wampserver了),环境搭建好后,到yii官方网站下载yii framework:http: ...

随机推荐

  1. 【BZOJ】【2223】【COCI 2009】PATULJCI

    可持久化线段树 同BZOJ 3524,但是不要像我一样直接贴代码……TAT白白WA了一次,so sad /*********************************************** ...

  2. 【POJ】【2348】Euclid‘s Game

    博弈论 题解:http://blog.sina.com.cn/s/blog_7cb4384d0100qs7f.html 感觉本题关键是要想到[当a-b>b时先手必胜],后面的就只跟奇偶性有关了 ...

  3. 剑指offer--面试题14--收获

    按照作者的说法,作为应届毕业生的我来说,如果能写出初级程序员的参考代码来解决面试题14就可认为过关了... 参考代码如下: void ReorderOddEven_1(int *pData, unsi ...

  4. intellij idea 14 ULTIMATE 注册码

    Name:happy KEY:63763-YCO0I-QR4TV-G4I3E-4XGK9-GQSQ3

  5. 解决eclipse打开报错:failed to create the java virtual ma

    在Eclipse安装目录下找到:eclipse.ini 将如下参数改为: --launcher.XXMaxPermSize 128M ------------------------------- 说 ...

  6. C# 常用的工具类

    编码解码.图片与byte[].日志文件写入和读取 /// <summary> /// 将字符串编码为Base64字符串 /// </summary> /// <param ...

  7. hdu 1596 find the safest road(最短路,模版题)

    题目 这是用Dijsktra做的,稍加改动就好,1000ms..好水.. #define _CRT_SECURE_NO_WARNINGS #include<string.h> #inclu ...

  8. REST_FRAMEWORK加深记忆-第二次练习官方文档

    我想,其它几个基于PYTHON的REST API模块概念都差不多吧. 先深入搞定这个吧. 前几次练习完了有一些印象,并且在工作中实践过一个,现在多弄几次,玩熟悉点. Serializers.py __ ...

  9. cojs QAQ的矩阵 题解报告

    题目描述非常的清晰 首先我们考虑(A*B)^m的求法,这个部分可以参考BZOJ 杰杰的女性朋友 我们不难发现(A*B)^m=A*(B*A)^(m-1)*B A*B是n*n的矩阵,而B*A是k*k的矩阵 ...

  10. Project Euler 99:Largest exponential 最大的幂

    Largest exponential Comparing two numbers written in index form like 211 and 37 is not difficult, as ...