Location: PHPKode > scripts > APC Chatt > chatter_object.php
<?php

/*
 *  This class can be used for online chat system such as single chat(online Consultant or for GeneralChat rooms )
 *  it Use one of PHP cache Containers APC memcahce etc for saving chat state
 * 
 *
 *
*/

interface chatter {

    public function create($what,$object);
    public function destry($what,$name);
    public function reply(rooms_users $room,$user);


}

/*
   *  -o-transform: scale(1.1);
    -moz-transform: scale(1.1);
    transform: scale(1.1);
         * zoom: 2;
         *
         *
*/


interface rooms_users {
    // This interface is more for relations
    public static function get_room();

    public function getInfo();

}

// BASE CHAT OBJECT

class  basechatter implements chatter {

    public $rooms = array();
    public $user= array();
    public $object;
    const ROOM = 1;
    const USER = 2 ;



    public function  __construct() {
        $this->object=$this;
    }



    public function create($what,$obj,$name=null) {




        if ($what ==1 ) {

            if (!array_key_exists($obj->name, $this->rooms)) {
                $this->rooms[$obj->name] = $obj;

            }


        }

        if ($what ==2 ) {

            if (!array_key_exists(spl_object_hash($obj), $this->user)) {
                $this->user[spl_object_hash($obj)] = $obj;
                print_r($obj);

                return  spl_object_hash($obj) ;
            }


        }


    }

    public function destry($what,$name) {

        if ($what == basechatter::ROOM ) {

            if (array_key_exists($name, $this->rooms)) {

                unset($this->rooms[$name]);

            }else return false;


        }

        if ($what == basechatter::USER ) {

            if (array_key_exists($name, $this->user)) {
                unset($this->user[$name]);

            }else return false;


        }


    }


    public function removeUser(rooms_users $user) {
        if (array_key_exists(spl_object_hash($user), $this->user)) {
            unset($this->user[$name]);
            return true;
        }else return false ;

    }


    public function getuser($name) {
        return $this->user[$name];


    }

    public function getRoom($name) {
        return $this->rooms[$name] ;
    }



    public function reply(rooms_users $room,$user) {
        $room->replys[$user->name]= $user->reply;
        $this->saveTOmem();
    }


    public function saveTOmem() {
        return new memento($this);
    }




    public function getreplys(rooms_users $room) {
        return $room->replys;
    }


    public function restoreState($mem) {



    }







}


/// Class  Rooms For Chating


class rooms  implements rooms_users {

    public $replys=array();
    public $maxusers;
    public $activ_users= array();
    const MAX_R = 100 ;


    public $name;
    public $description;

    public function __construct($name,$description,$maxusers=20) {
        $this->name= $name;
        $this->description  = $description;
        $this->maxusers = $maxusers;
        
    }


    public function  __toString() {
        return $this->name;

    }


    public function setReply($user,$reply) {
        if (count($this->replys)> self::MAX_R) $this->replys= array() ;
        $this->replys[$user."  ". strftime("%S %M %H",time())]=$reply;

    }


    public static function get_room() {
        return   $this;

    }


    public function addUsertoroom($user) {
        if(!array_key_exists($_SESSION["current_chat"], $this->activ_users)) {
            $this->activ_users[$_SESSION["current_chat"]]= $user;
        }
    }

    public function clear() {
        $this->replys = array();
        $this->activ_users = array();

    }

    public function get_users() {
        return $this->activ_users;
    }


    public function getInfo() {

        return array(
                "name"=>$this->name,
                "desc"=>$this->description,
                "maxusers"=>$this->maxusers,
                "users"=>$this->activ_users

        );

    }


}

/// User Objects


class users  implements rooms_users {

    public $replys=array();
    public $name;
    public $descr;
    public $email;
    public $current_room ;
    public $id;
    public $ip;
    public $type;

    const MAX_REPLYS = 10 ;


    public function set_reply($reply) {
        if (count($this->replys) > self::MAX_REPLYS ) $this->replys= array() ;
        $this->replys[] = $reply;

        foreach($this->replys as $r) $this->current_room->setReply($this,$r);


    }

    public function __construct($name,$email,$description,$type=1) {
        $this->name = $name;
        $this->email=$email;
        $this->type=$type;
        $this->descr  = $description;
        $this->ip=$_SERVER["REMOTE_ADDR"];
    }


    public function setRoom(rooms_users $room ) {

        $this->current_room = $room ;
        $room->addUsertoroom($this);


    }


    public static function get_room() {
        return   $this->current_room;

    }


    public function  __toString() {
        return $this->name;
    }


    public function getallreplys() {
        return $this->replys();
    }





    public function getInfo() {
        return array(
                "name"=>$this->name,
                "email"=>$this->email,
                "desc"=>$this->descr,
                "replys"=>$this->replys

        );


    }


}


/*
 *  storing objects states
 *
 *
*/


class memento {
    public $object;

    public function __construct($object,$name=null,$cahce='auto') {
        $this->object = $object;
        $cahcer= new Cache($cahce);
        $cahcer->put($name,serialize($object),1000);
    }


    public static  function getmeMem($name,$cache) {

        $cahcer= new Cache($cache);

        if (is_object(unserialize($cahcer->get($name)))){
         
        return unserialize($cahcer->get($name));



        }else return false; 

    }




}


// Here  we create builders for chatting

/*
 *
 *  Get me chat OR if Chat doesnot Exists Create it with default room
 *
 * 
 *
*/


abstract class chatsbuilder {

    public function getfrom_cache($options) {
        $cahcer= new Cache($options);
        if ($cahcer->get("CHATTER"))  return unserialize($cahcer->get("CHATTER")); else return false;

    }

    public function settocahce(chatter $ob,$options) {
        $cahcer= new Cache($options);
        if ($cahcer->put("CHATTER",serialize($ob),1000))  return true;

    }



}


class room_builder extends chatsbuilder {

    private $room ;

    public function  __construct($name,$desc,$max=20) {

        $this->room = new rooms($name, $desc,$max) ;
    }


    public function set_room(chatter $basechat) {
        $room = $this->room;
        $basechat->create(basechatter::ROOM,$room);


    }



}


class user_builder extends chatsbuilder {

    private $user =array();


    public function __construct($name,$email,$desc) {
        $this->user=array(
                "name"=>$name,
                "email"=>$email,
                "desc"=>$desc

        );

    }


    public function set_user(chatter $basechat) {

        if (!isset($_SESSION["current_chat"]) || isset($basechat->user[$_SESSION["current_chat"]])==false) {
            $user=new users($this->user["name"],$this->user["email"],$this->user["desc"],100);
            $_SESSION["current_chat"] = $basechat->create(basechatter::USER, $user);
        }



    }



}





class chatdirector extends chatsbuilder {

    public  $chat ;
    private $options;


    public function __construct($room=null,$user=null,$cacher='auto') {
        $this->options = $cacher;
              if ($this->getfrom_cache($cacher)) {
              $this->chat= $this->getfrom_cache($cacher);

                if (!isset($this->chat->user[$_SESSION["current_chat"]])) {

                       $user->set_user($this->chat);

                }


            if (!isset($_SESSION["current_chat"])) {
                $user->set_user($this->chat);

            }

        } else {

            $this->chat = new basechatter();



            /*  *
                     * Here we create Base Chat Object Create Rooms And users
                     *  *
            */
            // Create new user if not Exists
            $user->set_user($this->chat);
            // create new room if not exists
            $room->set_room($this->chat);

            $this->settocahce($this->chat,$cacher);

        }



    }

    public static function destroy() {
        $cahcer= new Cache();
        $cahcer->clearcache() ;
        session_destroy();
        return true  ;


    }

    public function chat() {




        return $this->chat;
    }

    public function save() {
        $this->settocahce($this->chat,$this->options);
    }







}


// THis is all ..



/*
      * This is my cache wrapper Here we used him to store chatMainObject with users And Chat rooms
      * 
      *
      *
*/



class Cache {

    var $_cache_type = 'auto'; // дефолтное значение
    var $_memcache = null;

    private $t,$syscach=array();




    public function getaviable() {
        $this->t=array();

        foreach ($this->syscach as $key=>$v) {
            $this->t[]= "<h3> ".$v."</h3>";
        }
        return $this->t;

    }




    function __construct($options = null) {
        // Проверка поддержки кеш-систем
        $cache_systems = array();

        if (class_exists('Memcache')) {
            $cache_systems[] = 'memcache';
            $this->syscach[]=   'memcache' ;
        }

        if (function_exists('eaccelerator_get')) {
            $cache_systems[] = 'eaccelerator';
            $this->syscach[]=   'eaccelerator' ;
        }
        if (function_exists('apc_fetch')) {
            $cache_systems[] = 'apc';
            $this->syscach[]=   'apc' ;
        }
        if (function_exists('xcache_get')) {
            $cache_systems[] = 'xcache';
            $this->syscach[]=   'xcache' ;
        }
        if (class_exists('Memcache')) {
            $cache_systems[] = 'memcache';
            $this->syscach[]=   'memcache' ;
        }

        $required_cache = isset($options['cache']) ? $options['cache'] : $this->_cache_type;




        if (count($cache_systems) && $required_cache != 'none') {
            if ($required_cache == 'auto') {
                $this->_cache_type = array_shift($cache_systems);



            }
            else if (in_array($required_cache, $cache_systems))
                $this->_cache_type = $required_cache;
            else
                $this->_cache_type = 'none';
        }
        else
            $this->_cache_type = 'none';

        if ($this->_cache_type == 'memcache') {

            $failed = true;

            if (isset($options['memcache']) && is_array($options['memcache'])) {

                $this->_memcache = new Memcache;

                foreach ($options['memcache'] as $server) {


                    if (!is_array($server) || !isset($server['host'])) // host должен быть указан
                        continue;

                    $server['port'] = isset($server['port']) ? (int) $server['port'] : ini_get('memcache.default_port');
                    $server['persistent'] = isset($server['persistent']) ? (bool) $server['persistent'] : true;

                    if ($this->_memcache->addServer($server['host'], $server['port'], $server['persistent']))
                        $failed = false;
                }

                if ($failed)
                    $this->_memcache = null;
            }

            if ($failed)    $this->_cache_type = 'none';
        }
    }

    function get($key) {
        $data = null;

        switch ($this->_cache_type) {
            case 'none':
                break;
            case 'eaccelerator':
                $data = eaccelerator_get($key);
                break;
            case 'apc':
                $data = apc_fetch($key);
                break;
            case 'xcache':
                $data = xcache_get($key);
                break;
            case 'memcache':
                $data = $this->_memcache->get($key);
                break;
        }

        return $data;
    }





    public function clearcache() {

        switch($this->_cache_type) {

            case 'eaccelerator':
                eaccelerator_clean();
                break;


            case 'apc':
                apc_clear_cache('user');
                break;




            case 'xcache':
                $list =$this->_memcache->getList();
                -      xcache_unset('pagecache_active_list');
                break;


            case 'memcache':
                $this->_memcache->flush();
                break;






        }

    }



    function put($key, $data, $ttl) {
        print_r($this->_cache_type);
        switch ($this->_cache_type) {
            case 'none':
                break;
            case 'eaccelerator':
                eaccelerator_put($key, $data, $ttl);
                break;
            case 'apc':

                apc_store($key, $data, $ttl);
                break;
            case 'xcache':
                xcache_set($key, $data, $ttl);
                break;
            case 'memcache':

            // Решение set() проблемы с несколькими серверами.
            // http://www.php.net/manual/ru/function.memcache-set.php#84032
                if (!$this->_memcache->replace($key, $data, MEMCACHE_COMPRESSED, $ttl))
                    $this->_memcache->set($key, $data, MEMCACHE_COMPRESSED, $ttl);

                break;
        }
    }
}





?>
Return current item: APC Chatt