<?php

namespace Business;
use Our\NameConst;

/**
 * 业务层的抽象类
 */
abstract class AbstractModel {
    public $clientType=NameConst::pcClient;

    /**
     * 不允许克隆对象
     */
    public function __clone() {
        trigger_error('Clone is not allow!', E_USER_ERROR);
    }
    public function __construct()
    {
        $this->init();
    }

    public function init(){

    }



    /**
     * 获取单条记录(优先从redis获取,如果redis不存在对应的数据,再从数据库从库取)
     * @param $where 查询条件
     * @param $tableName 数据库表明
     * @param $primaryKey 数据库主键
     * @param array $columns 需要查询的数据字段
     * @param null $redisTablename  redis对应表命名
     * @return mixed
     */
    public function findFromRedis($where,$tableName,$primaryKey,$columns = array('*'),$redisTablename=null){
        $redis = new  \Redis\AbstractModel();
        if(!$redisTablename){
            $redisTablename = $tableName;
        }
        $id = $where[$primaryKey];
        if($id){
            $redisKey = $redisTablename . \Redis\AbstractModel::DELIMITER . $id;
            $fullData = $redis->get($redisKey);
            $fullData = unserialize($fullData);
            if (!$fullData) {
                $memberMessageMysqlSlave=\Mysql\LinkMySQLModel::get();
                $fullData = $memberMessageMysqlSlave->from($tableName)->where(array($primaryKey=>$id))->fetchOne();
                if($fullData){
                    $redis->set($redisKey,serialize($fullData));
                }
            }
            if(count($columns)==1&&$columns[0]=='*'){
                $returnData = $fullData;
            }else{
                $returnData = array_intersect_key($fullData,array_flip($columns));
            }
            return $returnData;
        }else{
            $memberMessageMysqlSlave=\Mysql\LinkMySQLModel::get();
            $returnData = $memberMessageMysqlSlave->from($tableName)->where($where)->select($columns)->fetchOne();
            return $returnData;
        }
        return false;
    }


}