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. 1509: [NOI2003]逃学的小孩 - BZOJ

    Description Input 第一行是两个整数N(3  N  200000)和M,分别表示居住点总数和街道总数.以下M行,每行给出一条街道的信息.第i+1行包含整数Ui.Vi.Ti(1Ui ...

  2. DllImport的具体用法

    现在是更深入地进行探讨的时候了.在对托管代码进行 P/Invoke 调用时,DllImportAttribute 类型扮演着重要的角色.DllImportAttribute 的主要作用是给 CLR 指 ...

  3. CentOS下使用cmake编译安装mysql

    一.下载安装所必需的依赖包 1.因为高版本mysql都用cmake安装,所以下载cmake wget http://www.cmake.org/files/v3.0/cmake-3.0.1.tar.g ...

  4. Ubuntu环境下利用ant编译nutch2.2.1 & 配置nutch2.2.1

    /×××××××××××××××××××××××××××××××××××××××××/ Author:xxx0624 HomePage:http://www.cnblogs.com/xxx0624/ ...

  5. sql查询数据库中所有表的记录条数,以及占用磁盘空间大小。

    SELECT TableName = obj.name, TotalRows = prt.rows, [SpaceUsed(KB)] = SUM(alloc.used_pages)* FROM sys ...

  6. 独立IP与共享IP的区别

    做网站选择独立IP还是共享IP,相信很多站长都在此纠结过,自己不使用服务器的时候从来没有关心过独立IP和共享IP的究竟有什么具体的差别.但当自己真正用到的时候,才发现:同样都是 IP,差别不是一般的大 ...

  7. linux上应用程序的执行机制

    linux上应用程序的执行机制 执行文件是如何在shell中被"执行"的.本文中尽可能少用一些源码,免得太过于无 聊,主要讲清这个过程,感兴趣的同学可以去查看相应的源码了解更多的信 ...

  8. 函数执行到return就结束了

    遇到return,函数就结束了,不会往下执行 测试: class User { String name; int age; boolean fun1(int i){ if(i==1){ return ...

  9. iOS:自定义工具栏、导航栏、标签栏

    工具栏为UIToolBar,导航栏UINavigationBar,标签栏UITabBar.它们的样式基本上时差不多的,唯一的一点区别就是,工具栏一般需要自己去创建,然后添加到视图中,而导航栏和标签栏不 ...

  10. CMake学习(1)---简单程序与库

    cmake是linux平台下重要的工具,可以方便的组织makefile.之前一直在windows平台下进行软件开发,在vs2010的IDE里,只要一点run程序就能跑出结果.但是程序的编译并没有那么简 ...