yii2.0 基于ActiveRecord 封装的curd操作
最近在用yii2.0 进行系统重构,需要一个兼容之前框架的curd 的一种调用方式,所以对activeRecord 类进行了继承和封装,实现基本的curd、强制主从切换等方法,同时兼容ActiveRecord 的原生方法。
代码如下:
<?php
/**
* Created by PhpStorm.
* User: wangyaofeng
* Date: 17-8-11
* Time: 下午12:06
*/
namespace commoncomponents;
use Yii;
use yiidbActiveRecord;
abstract class ModelBasic extends ActiveRecord
{
//标志位 是否强制走主库
protected static $_master = false;
//标志位 数据库配置对应的key
protected static $_configKey = "Shop";
//对应的表明
protected static $_tableName = "shop";
//对应的表前缀
protected static $_tablePrefix = "cc_";
public $param = array();
protected static $_dbArray = array();
protected $_transaction = null;
//配置参数
public function setParam($_configKey,$tableName,$_tablePrefix="cc_"){
self::$_configKey = $_configKey;
self::$_tableName = $tableName;
self::$_tablePrefix = $_tablePrefix;
}
//配置表名
public static function tableName()
{
return "{{%".self::$_tableName."}}";
}
//配置db主从和前缀配置
public static function getDbConfig($configName="Shop",$master=false){
$config = Yii::$app->params[$configName];
//应对库相同,表前缀不同的情况
$config["masterConfig"]["tablePrefix"] = self::$_tablePrefix;
$config["slaveConfig"]["tablePrefix"] = self::$_tablePrefix;
$key = md5($configName);
/*if(!isset(self::$_dbArray[$key])){
self::$_dbArray[$key] = Yii::createObject($config);
}*/
//返回主库实例
if(!isset(self::$_dbArray[$key])){
self::$_dbArray[$key] = Yii::createObject($config);
}
switch ($master){
case false:return self::$_dbArray[$key]->getSlave();break;
case true:return self::$_dbArray[$key]->getMaster();break;
default:return self::$_dbArray[$key];
}
//返回从库实例
}
//重写 ActiveRecord 静态方法 根据参数切换主从
public static function getDb(){
return self::getDbConfig(self::$_configKey,self::$_master);
}
//查询方法
public function selectLogic($field,$where,$order,$limit,$page,$count=false,$master=false){
try{
//要求强制切主或者 有事务存在的时候 要切回主库
if($master==true || !empty($this->_transaction)){
self::$_master = true;
}else{
self::$_master = false;
}
$offset = ($page-1)*$limit;
$basic = $this->find()->where($where)->orderBy($order)->limit($limit)->offset($offset)->select($field);
$result["data"] = $basic->asArray()->all();
//$sql = $basic->createCommand()->getRawSql();
if($count==true){
$result["count"] = $this->find()->where($where)->count("*");
}
return $result;
}catch (Exception $e){
return $e->getMessage();
}
}
//插入方法 强制切主 如果主键id存在返回主键id,否则返回 true/false
public function insertLogic($data = array()){
self::$_master = true;
foreach($data as $key=>$val){
$this->$key = $val;
}
$result = $this->insert();
$insertId = $this->primaryKey;
if($result==true && !empty($insertId)){
return $insertId;
}
return $result;
}
//批量插入方法 强制切主
public function insertAllLogic($data = array()){
self::$_master = true;
$columns = array();
$rows = array();
foreach($data as $key =>$val){
$rows[$key] = array_values($val);
if(empty($columns)){
$columns = array_keys($val);
}
}
$basic = self::getDb()->createCommand();
$result = $basic->batchInsert(self::$_tablePrefix.self::$_tableName,$columns,$rows)->execute();
//var_dump($basic->getRawSql());
return $result;
}
//更新方法
public function updateLogic($data,$where){
self::$_master = true;
$result = $this->updateAll($data,$where);
//var_dump($this->find()->createCommand()->getRawSql());
return $result;
}
//update更新 是否带校验
public function updateLoginc2($data,$where,$runValidation=false){
self::$_master = true;
$model = $this->findOne($where);
foreach($data as $key=>$val){
$model->$key = $val;
}
$result = $model->update($runValidation);
return $result;
}
//删除方法
public function deleteLogic($where){
self::$_master = true;
$result = $this->deleteAll($where);
return $result;
}
//开启一个事物
public function begin(){
//事物应该在主库才会生效 因为自动走的读写分离,写是主库
self::$_master = true;
$this->_transaction = self::getDb()->beginTransaction();
}
//提交一个事物
public function commit(){
if(!empty($this->_transaction)){
$this->_transaction->commit();
}
}
//回退一个事物
public function rollback(){
if(!empty($this->_transaction)){
$this->_transaction->rollBack();
}
}
}调用实例:
<?php
/**
* Created by PhpStorm.
* User: wangyaofeng
* Date: 17-8-24
* Time: 下午5:02
*/
namespace backendmodelsshop;
use commoncomponentsModelBasic;
class AdminRecall extends ModelBasic
{
/**
* 初始化 配置 实例
* @since 2017-08-31
* @lastModifyTime 2017-08-31
* @author
* @lastModify
* @return null
*/
public function __construct()
{
//db配置对应的key
$this->param["configKey"] = "Shop";
//表名
$this->param["tableName"] = "admin_recall";
//前缀
$this->param["tablePrefix"] = "cc_";
//设置配置
$this->setParam($this->param["configKey"],$this->param["tableName"],$this->param["tablePrefix"]);
}
/**
* 插入 数据 实例
* @since 2017-08-31
* @lastModifyTime 2017-08-31
* @author
* @lastModify
* @return null
*/
public function create()
{
//开启事物
$this->begin();
$time = time();
$array["valid_starttime"] = $time;
$array["valid_endtime"] = $time+86400;
$array["require"] = "test";
$result = $this->insertLogic($array);
//回滚测试
$this->rollback();
return $result;
}
/**
* 批量插入 数据 实例
* @since 2017-08-31
* @lastModifyTime 2017-08-31
* @author
* @lastModify
* @return MaxId
*/
public function createAll()
{
$time = time();
for($i=0;$i<1;$i++){
$array[$i]["valid_starttime"] = $time;
$array[$i]["valid_endtime"] = $time+86400;
$array[$i]["require"] = "test".$i;
}
//开始事物
$this->begin();
$result = $this->insertAllLogic($array);
//事物提交实例
$this->commit();
return $result;
}
/**
* 更新 数据 实例
* @since 2017-08-31
* @lastModifyTime 2017-08-31
* @author
* @lastModify
* @return int/num
*/
public function updateTest()
{
$data["require"] = "hi,test";
$where= array("in","id",array("141","140"));
$result = $this->updateLogic($data,$where);
return $result;
}
/**
* 删除 数据 实例
* @since 2017-08-31
* @lastModifyTime 2017-08-31
* @author
* @lastModify * @return true/false */ public function deleteTest() { $where["id"] = 141; $result = $this->deleteLogic($where); return $result; } /** * 查询 数据 实例 * @since 2017-08-31 * @lastModifyTime 2017-08-31 * @author * @lastModify * @return array */
public function selectTest() { $where = [ "and", ["<", "valid_starttime", 1503575727], [ "and", [">=", "id", "100"], ["<=", "id", "105"], ] ]; $reslut = $this->selectLogic("*",$where," id desc ",10,1,false,false); return $reslut; }}
<?php
/**
* Created by PhpStorm.
* User: wangyaofeng
* Date: 17-8-11
* Time: 上午11:10
*/
//数据库配置,支持 主从,多数据库配置
return [
/*多数据库支持*/
"Shop" => [
"class" => "yiidbConnection",
"tablePrefix" =>"cc_",
"masterConfig" => [
"username" => "test",
"password" => "test1",
//"dsn" => "mysql:host=127.0.0.1;dbname=shop;port=5500",
"charset" =>"utf8",
],
"masters" => [
["dsn" => "mysql:host=127.0.0.1;dbname=shop;port=5500"],
],
// 配置从服务器
"slaveConfig" => [
"username" => "test",
"password" => "test1",
"charset" => "utf8",
"tablePrefix" =>"cc_",
"attributes" => [
PDO::ATTR_TIMEOUT => 10,
],
],
// 配置从服务器组
"slaves" => [
["dsn" => "mysql:host=127.0.0.1;dbname=shop;port=5500"],
],
],
/*5500 test*/
"ShopAdmin" =>[
"class" => "yiidbConnection",
"tablePrefix" =>"cc_",
"masterConfig" => [
"username" => "test_admin",
"password" => "*********",
"charset" =>"utf8",
],
"masters" => [
["dsn" => "mysql:host="";dbname=shop_admin;port=5500"],
],
// 配置从服务器
"slaveConfig" => [
"username" => "test_admin",
"password" => "**********",
"charset" => "utf8",
"tablePrefix" =>"cc_",
"attributes" => [
PDO::ATTR_TIMEOUT => 10,
],
],
// 配置从服务器组
"slaves" => [
["dsn" => "mysql:host="";dbname=shop_admin;port=5500"],
],
]
];
yii2.0 自带ActiveRecord 方法原生支持,只是对其进行了一层封装,可以作为model 基类使用,使得db操作更加灵活,查询(selectLogic)时通过参数还可以强制主从切换,这里是用作重构过程中更好的利用一些代码,而做的一层封装和基础方法收拢,从封装的model基类不在显示支持链表查询,分享出来仅供参考!
声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。
- 上一篇: jquery 判断当前上传文件大小限制上传格式 搭配thinkphp实现上传即预览(模拟异步上传)
- 下一篇:没有了
