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. Spring中HibernateCallback的用法(转)

    Hibernate的复杂用法HibernateCallback HibernateTemplate还提供一种更加灵活的方式来操作数据库,通过这种方式可以完全使用Hibernate的操作方式.Hiber ...

  2. PHP之SQL防注入代码集合(建站常用)

    SQL防注入代码一 <?php if (!function_exists (quote)) { function quote($var) { if (strlen($var)) { $var=! ...

  3. TensorFlow 基本使用

    使用 TensorFlow, 你必须明白 TensorFlow: 使用图 (graph) 来表示计算任务. 在被称之为 会话 (Session) 的上下文 (context) 中执行图. 使用 ten ...

  4. 【WCF--初入江湖】目录

    [WCF--初入江湖]目录 [WCF--初入江湖]01 WCF编程概述 [WCF--初入江湖]02 WCF契约 [WCF--初入江湖]03 配置服务 [WCF--初入江湖]04 WCF通信模式 [WC ...

  5. cf 363D

    贪心加二分 虽然比赛后才过 ........ /************************************************************************* &g ...

  6. 从后端到页面:如何全方位监控 Ruby 应用?

    [编者按]本文参考技术分享 ,由 OneAPM 工程师补充整理,并且已经征得原作者的同意. 为什么选择 OneAPM ? 在性能监控领域,业界比较有名的是 New Relic 还有 Appdynami ...

  7. Dijsktra算法C++实现

    Dijsktra算法解决了有向图G=(V,E)上带权的单源最短路径问题.但要求所有边的权值非负. 思想:Dijkstra算法中设置了一顶点集合S,从源点s到集合中的顶点的最终最短路径的权值均已确定.算 ...

  8. javascript-权威指南读书笔记(1)

    <script type="text/javascript"> //数组与object的关系 var obj = { name: "刘建伟", Ag ...

  9. Jedis 操作

    http://www.cnblogs.com/liuling/p/2014-4-19-04.html

  10. 1.Spring IoC简单例子

    Spring IoC简单例子 1.IHelloMessage.java package com.tony.spring.chapter01; public interface IHelloMessag ...