Advertisement
terorama

mvc / base.inc.php

Dec 22nd, 2012
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 28.22 KB | None | 0 0
  1. <?php
  2.  
  3. //----------------------------------------------
  4. //              base classes
  5. //----------------------------------------------
  6. class DBConn {
  7.    private static $_db=0;
  8.    
  9.    private static $DB_HOST;
  10.    private static $DB_USER;
  11.    private static $DB_PASSWORD;
  12.    private static $DB_NAME;
  13.    
  14.    //----------------------------------
  15.    public static function connect() {
  16.    
  17.       self::$_db = @new mysqli (self::$DB_HOST, self::$DB_USER, self::$DB_PASSWORD, self::$DB_NAME );
  18.      
  19.       if (self::$_db->connect_errno) {
  20.      
  21.          throw new Exception('connection error '.self::$_db->connect_error);
  22.       }
  23.  
  24.    }
  25.    
  26.    //----------------------------------
  27.    public static function set($DB_HOST, $DB_USER, $DB_PASSWORD, $DB_NAME) {
  28.    
  29.       self::$DB_HOST = $DB_HOST;
  30.       self::$DB_USER = $DB_USER;
  31.       self::$DB_PASSWORD = $DB_PASSWORD;
  32.       self::$DB_NAME = $DB_NAME;
  33.    }
  34.    
  35.    //----------------------------------
  36.    public static function get() {
  37.       if (self::$_db==0) {
  38.          self::connect();
  39.       }
  40.      
  41.       return self::$_db;
  42.    }
  43. }
  44.  
  45. //----------------------------------------------
  46. //               Debugger
  47. //----------------------------------------------
  48. class Debugger {
  49.  
  50.  
  51.    private static $_prepared = false;
  52.    private static $_debugFile ='';
  53.    private static $_buffer ='';
  54.    
  55.    //---------------------------------
  56.    private static function isDebugFile() {
  57.    
  58.       return (bool)self::$_debugFile;
  59.    }
  60.    //---------------------------------
  61.    private static function prepared() {
  62.    
  63.       if (self::$_prepared)
  64.          return true;
  65.          
  66.        if (isset($_SESSION['debug_prepared'])) {
  67.        
  68.           if (isset($_SESSION['debug_file']))            
  69.              self::$_debugFile = $_SESSION['debug_file'];
  70.              
  71.           self::$_prepared = true;
  72.           return true;
  73.        }
  74.        
  75.        return false;
  76.    }
  77.    //-------------------------------------------------save session variable  
  78.    private static function save_to_session($name,$value) {
  79.    
  80.        if (function_exists('session_status')) {
  81.          if (session_status()==PHP_SESSION_ACTIVE)
  82.             $_SESSION[$name] = $value;
  83.             }
  84.        else
  85.           if (session_id()!=='')
  86.              $_SESSION[$name] = $value;
  87.    }
  88.    //--------------------------------- reset debugger
  89.    public static function reset() {
  90.      
  91.       if (isset($_SESSION['debug_prepared']))
  92.          unset ($_SESSION['debug_prepared']);
  93.    
  94.       if (isset($_SESSION['debug_file']))
  95.          unset ($_SESSION['debug_file']);
  96.    
  97.       self::$_debugFile = '';  
  98.       self::$_prepared = false;
  99.    }
  100.    //--------------------------------- prepare file
  101.    private static function prepare_file() {
  102.    
  103.       if (!file_exists(ROOT.DS.'logs'))
  104.          mkdir (ROOT.DS.'logs');
  105.          
  106.       self::$_debugFile = ROOT.DS.'logs'.DS.'debug_'.date('d_m_Y_H_i_s').rand(100,500).'.txt';
  107.       self::save_to_session('debug_file', self::$_debugFile);
  108.      
  109.    }
  110.    
  111.    //------------------------------------ output buffer
  112.    private static function outputBuffer() {
  113.      
  114.       if (self::isDebugFile()) {
  115.      
  116.          $link = substr(self::$_debugFile, strpos(self::$_debugFile, 'logs'.DS));        
  117.          echo 'debug information in file: <a href="'.$link.'">'.$link.'</a>';
  118.       }
  119.       else
  120.          echo '<h2>debug information</h2><div style="font-family:courier new">'.self::$_buffer.'</div>';
  121.    }
  122.    
  123.    //------------------------------------ error handler
  124.    
  125.    public static function errorHandler($number, $message, $file, $line) {
  126.      
  127.       echo '<h2>error occured</h2>';
  128.       echo '<p>'.str_pad('error number: ',30,' ',STR_PAD_RIGHT).$number.'</p>';
  129.       echo '<p>'.str_pad('error message: ',30,' ',STR_PAD_RIGHT).$message.'</p>';
  130.       echo '<p>'.str_pad('error in file: ',30,' ',STR_PAD_RIGHT).$file.'</p>';
  131.       echo '<p>'.str_pad('error in line: ',30,' ',STR_PAD_RIGHT).$line.'</p>';
  132.      
  133.       self::outputBuffer();
  134.    }
  135.    
  136.    //----------------------------------- exception handler
  137.    
  138.    public static function exceptionHandler($exception) {
  139.      
  140.       echo '<h2>exception occured</h2>';
  141.       echo '<p>'.str_pad('exception code: ',30,' ',STR_PAD_RIGHT).$exception->getCode().'</p>';
  142.       echo '<p>'.str_pad('exception message: ',30).$exception->getMessage().'</p>';
  143.       echo '<p>'.str_pad('exception in file: ',30).$exception->getFile().'</p>';
  144.       echo '<p>'.str_pad('exception in line: ',30).$exception->getLine().'</p>';
  145.      
  146.       //echo '<h3>exception trace</h3>';     
  147.       //echo '<pre>'.print_r($exception->getTrace(),true).'</pre>';
  148.      
  149.       self::outputBuffer();
  150.    }
  151.    
  152.    //----------------------------------- shutdown handler
  153.    
  154.    public static function shutdownHandler() {
  155.    
  156.       $error = error_get_last();
  157.      
  158.       echo '<h2>script finished</h2>';
  159.       echo 'error: <pre>'.print_r($error,true).'</pre>';
  160.      
  161.       self::outputBuffer();
  162.    }
  163.    
  164.    //--------------------------------- prepare debugger
  165.    public static function prepare() {
  166.      
  167.       if (!defined('DEBUG_MODE') || (!DEBUG_MODE))
  168.          return;
  169.      
  170.       if (self::prepared())
  171.          return;
  172.    
  173.       error_reporting(E_ALL);
  174.       ini_set('display_errors','On');
  175.    
  176.       set_error_handler (array('Debugger','errorHandler'));
  177.       set_exception_handler (array('Debugger','exceptionHandler'));
  178.       register_shutdown_function (array('Debugger','shutdownHandler'));
  179.      
  180.       if (defined('DEBUG_FILE') && (DEBUG_FILE==true))
  181.          self::prepare_file();
  182.        
  183.       self::$_buffer = '';
  184.       self::$_prepared = true;
  185.       self::save_to_session('debug_prepared', self::$_prepared);     
  186.    }
  187.    //--------------------------------- handle & write info
  188.    
  189.    public static function writeInfo($info, $className, $method) {
  190.    
  191.       if (!defined('DEBUG_MODE') || (!DEBUG_MODE))
  192.          return;
  193.                
  194.       self::prepare();
  195.      
  196.          
  197.       $s = str_repeat('-',50)."\r\n";    
  198.       $s  .= date('d.m.Y H:i:s').'  class: '.$className.' method: '.$method. "\r\n";
  199.       $s  .= str_repeat('-',50)."\r\n";
  200.      
  201.       $inf = array();
  202.       if (!is_array($info)) {
  203.          $inf[] = $info;
  204.       } else
  205.          $inf = $info;
  206.    
  207.       $s .= '<pre>'.print_r($inf, true).'</pre>';
  208.      
  209.       if (self::isDebugFile()) {
  210.          if (!file_exists(self::$_debugFile))
  211.          
  212.             $f = fopen (self::$_debugFile,'w');
  213.          else
  214.             $f = fopen (self::$_debugFile,'a');
  215.  
  216.          fwrite($f, $s);
  217.          fclose($f);         
  218.       }
  219.          
  220.       self::$_buffer .= nl2br($s);
  221.    }
  222. }
  223.  
  224.  
  225. //----------------------------------------------
  226. //              Controller
  227. //----------------------------------------------
  228. abstract class Controller {
  229.  
  230.    protected $_model;
  231.    protected $_controller;
  232.    protected $_action;
  233.    protected $_view;
  234.    
  235.    protected $_routes;
  236.    
  237.    protected $_params=array();
  238.    
  239.    //---------------------------- debug information
  240.    protected function _w($info, $method) {
  241.    
  242.       $className = get_class($this);
  243.       Debugger::writeInfo($info, $className, $method);
  244.    }
  245.    
  246.    //---------------------------- collect session and input parameters
  247.      
  248.    private function getSessionParams() {
  249.    
  250.       if (!isset($_SESSION))
  251.          return;
  252.          
  253.       foreach ($_SESSION as $key=>$val) {
  254.          
  255.          foreach ($this->_params as $pkey=>$pval) {
  256.          
  257.             if ($key==$pkey) {
  258.                $this->_params[$pkey]=$_SESSION[$key];
  259.             }
  260.          }
  261.       }  
  262.       $this->_w( $this->_params, __METHOD__);
  263.    }
  264.    //--------------------------------
  265.    private function getInputParams() {
  266.      
  267.       foreach ($_REQUEST as $key=>$val) {
  268.          
  269.          foreach ($this->_params as $pkey=>$pval) {
  270.            
  271.             if ($key==$pkey) {
  272.                $this->_params[$pkey]=$_REQUEST[$key];
  273.                
  274.                $_SESSION[$pkey] = $this->_params[$pkey];
  275.             }
  276.          }
  277.       }
  278.    }
  279.    
  280.    //---------------------------------- get related controllers
  281.    public function related() {
  282.       return array();
  283.    }
  284.    
  285.    //---------------------------------- declare expected GET parameters
  286.    
  287.    abstract protected function declareParams();
  288.    
  289.    //--------------------------------get parameters
  290.    private function getParams() {
  291.    
  292.       $this->getSessionParams();
  293.       $this->getInputParams();
  294.    }
  295.    
  296.    
  297.    //---------------------------------------init
  298.    
  299.    public function __construct($model, $view, $controller, $action) {
  300.      
  301.       $this->_controller = $controller;
  302.       $this->_model = $model;
  303.       $this->_action = $action;
  304.       $this->_view = $view;
  305.      
  306.       $this->$model =  new $model;
  307.       $this->_view =   new $view($action, $controller, $this->_routes);
  308.      
  309.       //-----------------params
  310.       $this->declareParams();
  311.       $this->getParams();
  312.    }
  313.    
  314.    //----------------------------------   properties get handler
  315.    public function __get($name) {
  316.    
  317.       if (substr($name,0,3)=='p__') {
  318.      
  319.          $paramName = substr($name,3);
  320.          
  321.          if (array_key_exists($paramName, $this->_params))
  322.          
  323.             return $this->_params[$paramName];
  324.          else
  325.             return false;
  326.       }
  327.    }
  328.    
  329.    //----------------------------------   common dispatching operations
  330.    
  331.    abstract protected function commonDispatch();
  332.    
  333.    //----------------------------------   dispatch current action
  334.    public function dispatch() {
  335.    
  336.       $this->commonDispatch();
  337.      
  338.       //$this->_w($this->_action,__METHOD__);
  339.      
  340.       if ((int)method_exists($this, $this->_action)) {
  341.        
  342.          call_user_func (array($this, $this->_action));
  343.       }
  344.    }
  345.    
  346.    //---------------------------------   set view variable
  347.    protected function set($name, $value) {
  348.      
  349.       $this->_view->set($name, $value);
  350.    }
  351.    //---------------------------------   set block of view variables
  352.    protected function setAll($el) {
  353.    
  354.       foreach ($el as $key=>$value) {
  355.          $this->set($key,$value);
  356.       }
  357.    }  
  358.    //--------------------------------------   render view
  359.    function render($retblocks=true, $tmpl='') {
  360.    
  361.       return $this->_view->render($retblocks, $tmpl);
  362.    }
  363. }
  364.  
  365. //----------------------------------------------
  366. //               form input
  367. //----------------------------------------------
  368. class stdInput {
  369.    
  370.    private $_type;
  371.    private $_name;
  372.    private $_value;
  373.    private $_values = array();
  374.    private $_label = '';
  375.    private $_labels = array();
  376.    
  377.    private $_handlers = array();
  378.    //--------------------------------   constructor
  379.    
  380.    public function __construct($type, $name, $value, $label='') {
  381.      
  382.       $this->_type = $type;
  383.       $this->_name = $name;
  384.      
  385.       //-------------------- checkboxes and radiogroups
  386.       if (is_array($value)) {
  387.          
  388.          for ($i=0; $i<count($value); $i++) {
  389.            
  390.             $el = array();
  391.             if (substr($value[$i], strlen($value[$i])-1,1)=='*') {
  392.            
  393.                $el['checked']=true;
  394.                $el['value'] = substr($value[$i],0,strlen($value[$i])-1);
  395.             } else {
  396.            
  397.                $el['checked']=false;
  398.                $el['value'] = $value[$i];
  399.             }
  400.             $this->_values[] = $el;        
  401.          }       
  402.       } //------- single components ( text / password / button / submit /reset )     
  403.       else {
  404.          $this->_value = $value;
  405.       }
  406.       //------------------------- labels
  407.       if (is_array($label)) {
  408.          for ($i=0; $i<count($label); $i++) {
  409.             $this->_labels[] = $label[$i];
  410.          }
  411.       } else {
  412.          $this->_label = $label;
  413.       }
  414.    }  
  415.    //-------------------------------------------   add handler
  416.    public function addHandler ($handler) {
  417.      
  418.       $this->_handlers[] = array ('event'=>$handler[0], 'handler'=>$handler[1]);
  419.    }
  420.    //------------------------------   draw input
  421.    public function draw() {
  422.    
  423.       $s = '';
  424.       $handlers_str = '';
  425.      
  426.       for ($i=0; $i<count($this->_handlers); $i++) {
  427.      
  428.          $handlers_str .= $this->_handlers[$i]['event'].'="'.$this->_handlers[$i]['handler'].'" ';
  429.       }
  430.      
  431.       switch (strtolower($this->_type)) {
  432.          //--------------------------
  433.          case 'text': case 'password': case 'submit':
  434.          case 'reset': case 'button': case 'file': case 'hidden':
  435.          
  436.             if ($this->_label) {
  437.                $s .= "<label for=\"{$this->_name}\">{$this->_label}</label>";            
  438.             }
  439.            
  440.             $s .= "<input $handlers_str type=\"{$this->_type}\" ".
  441.                   "name=\"{$this->_name}\" value=\"{$this->_value}\" />";
  442.             break;
  443.          //--------------------------
  444.          case 'textarea':
  445.             if ($this->_label)
  446.                $s .= "<p>{$this->_label}</p>";
  447.            
  448.             $s .= "<textarea $handlers_str name=\"{$this->_name}\">{$this->_value}</textarea><br/>";
  449.             break;
  450.            
  451.          //--------------------------
  452.          case 'radio': case 'checkbox':
  453.             for ($i=0; $i<count($this->_values); $i++) {
  454.            
  455.                $checked = ($this->_values[$i]['checked']) ? 'checked' : '';
  456.                
  457.                $s .= "<p><input $handlers_str type=\"{$this->_type}\" ".
  458.                      " name=\"{$this->_name}\" value=\"{$this->_values[$i]['value']}\" $checked />";
  459.                      
  460.                $s .= $this->_labels[$i].'</p>';  
  461.             }
  462.             break;
  463.            
  464.          //--------------------------
  465.          case 'select':
  466.             $s = "<select $handlers_str name=\"{$this->_name}\">";
  467.             for ($i=0; $i<count($this->_values); $i++) {
  468.                
  469.                $selected = ($this->_values[$i]['checked']) ? 'selected' : '';
  470.                $s .= "<option value=\"{$this->_values[$i]['value']}\" $selected >";
  471.                $s .= $this->_labels[$i].'</option>';
  472.             }
  473.             $s .= '</select><br/>';
  474.             break;
  475.       }
  476.      
  477.       return $s;
  478.    }
  479. }
  480.  
  481. //----------------------------------------------
  482. //               form fieldset
  483. //----------------------------------------------
  484. class stdFieldset {
  485.    
  486.    private $fields = array();
  487.    private $legend;
  488.    
  489.    //------------------------------------ constructor
  490.    public function __construct($legend) {
  491.      
  492.       $this->legend = $legend;
  493.    }
  494.    
  495.    //------------------------------   add field
  496.    
  497.    public function addField($type, $name, $value, $label) {
  498.      
  499.       $a = new stdInput ($type, $name, $value, $label);
  500.       $this->fields[] = & $a;
  501.      
  502.    }
  503.    //------------------------------   draw field
  504.    
  505.    public function draw() {
  506.      
  507.       $s = "<fieldset><legend>{$this->legend}</legend>";
  508.      
  509.       for ($i=0; $i<count($this->fields); $i++)
  510.          $s .= $this->fields[$i]->draw();
  511.          
  512.       $s .= '</fieldset>';
  513.       return $s;
  514.    }
  515.    
  516. }
  517.  
  518. //----------------------------------------------
  519. //                  Form
  520. //----------------------------------------------
  521. class stdForm {
  522.    
  523.     private $_action_route;
  524.    
  525.     private $scripts = array();
  526.     private $fieldsets = array();
  527.     private $hidden_fields = array();
  528.     private $buttons = array();
  529.    
  530.     //-------------------------   debug information
  531.    
  532.     protected function _w($info, $method) {
  533.    
  534.       $className = get_class($this);
  535.       Debugger::writeInfo($info, $className, $method); 
  536.     }  
  537.     //-------------------------   check if empty
  538.    
  539.     public function nzz($var, $default) {
  540.        return (isset($var)) ? $var : $default;
  541.     }
  542.     //-------------------------   constructor
  543.    
  544.     public function __construct($action_route, $onsubmit="") {
  545.        
  546.        $this->_action_route = $action_route;
  547.        
  548.        if (is_array($onsubmit)) {
  549.          
  550.           $this->scripts['onsubmit'] = array ('handler'=>$onsubmit[0], 'script'=>$onsubmit[1]);
  551.        }
  552.     }  
  553.     //--------------------------   add fieldset
  554.    
  555.     public function addFieldset ($legend) {
  556.        
  557.        $a = new stdFieldset($legend);
  558.        $this->fieldsets[] = & $a;
  559.        return $a;
  560.     }  
  561.     //--------------------------   add hidden field
  562.    
  563.     public function addHidden ($name, $value) {
  564.    
  565.        $this->hidden_fields[] = new stdInput ('HIDDEN', $name, $value);
  566.     }  
  567.     //--------------------------   add button
  568.    
  569.     public function addButton ($type, $name, $value, $onclick='') {
  570.        
  571.        if (is_array($onclick)) {       
  572.           $this->scripts[$name] = array ('handler'=>$onclick[0], 'script'=>$onclick[1]);  
  573.        }
  574.        
  575.        $a = new stdInput ($type, $name, $value);
  576.        
  577.        if (is_array($onclick))
  578.           $a->addHandler(array('onclick', $onclick[0]));
  579.          
  580.        $this->buttons[] = & $a;
  581.     }  
  582.     //---------------------------   draw header
  583.    
  584.     private function drawHeader() {
  585.        
  586.        $s = '<script type="text/javascript">';
  587.        foreach ($this->scripts as $script) {
  588.        
  589.           $s .= $script['script'];
  590.        }
  591.        $s .= '</script>';
  592.        
  593.        $subm = (isset($this->scripts['onsubmit'])) ?
  594.                          'onsubmit="'.$this->scripts['onsubmit']['handler'].'"':'';
  595.                          
  596.        $s .= '<form '.$subm. ' action="'.$this->_action_route.'" method="post" '.
  597.              ' enctype="application/x-www-form-urlencoded" >'; 
  598.  
  599.        return $s;            
  600.     }  
  601.     //---------------------------   draw footer
  602.    
  603.     private function drawFooter() {
  604.        
  605.        return '</form>';
  606.     }  
  607.     //---------------------------   draw form
  608.     public function draw() {
  609.    
  610.        $s = '';
  611.        $s .= $this->drawHeader();
  612.        
  613.        $func = create_function('$a',' echo $a->draw();');
  614.        
  615.        ob_start();     
  616.        array_walk($this->fieldsets, $func);
  617.        array_walk($this->hidden_fields, $func);
  618.        array_walk($this->buttons, $func);      
  619.        $s .= ob_get_contents();
  620.        ob_end_clean();
  621.        
  622.        $s .= $this->drawFooter();
  623.        return $s;
  624.     }
  625.    
  626.    
  627.    
  628. }
  629.  
  630.  
  631. //----------------------------------------------
  632. //                   View
  633. //----------------------------------------------
  634. abstract class View {
  635.    
  636.    protected $variables = array();
  637.    protected $_action;
  638.    protected $_controller;
  639.    
  640.    protected $_routes;
  641.    
  642.    protected $_blocks =array('header'=>'','content'=>'','sidebar'=>'','footer'=>'');
  643.    
  644.    protected $_stdtemplate = '<div id="%viewid%">
  645.       <div class="header">%header%</div>
  646.       <div class="content">%content%</div>
  647.       <div class="sidebar">%sidebar%</div>
  648.       <div class="footer">%footer%</div></div>';
  649.  
  650.    //---------------------------- debug information
  651.    protected function _w($info, $method) {
  652.    
  653.       $className = get_class($this);
  654.       Debugger::writeInfo($info, $className, $method);
  655.    }  
  656.    //-------------------------   constructor
  657.    
  658.    public function __construct($action, $controller, $routes) {
  659.    
  660.       /*$this->_w(array('action'=>$action,
  661.            'controller'=>$controller, 'routes'=>$routes), __METHOD__ );*/
  662.            
  663.       $this->_action = $action;
  664.       $this->_controller = $controller;
  665.       $this->_routes = $routes;
  666.    }
  667.    
  668.    //-------------------------   func calls handler
  669.    public function __call($name, $arguments) {
  670.    
  671.       //$this->_w(array('name'=>$name, 'args'=>$arguments),__METHOD__);
  672.      
  673.       if (substr($name, 0, 6 )=='route_') {
  674.      
  675.          $routeName = substr ($name, 6);
  676.          
  677.          return $this->getRoute($routeName, isset($arguments[0]) ? $arguments[0] :'');
  678.       }
  679.    }
  680.    
  681.    //-----------------------------------   properties get handler
  682.    public function __get($name) {
  683.      
  684.       if (substr($name,0,2)=='v_') {
  685.          
  686.          $varName = substr($name, 2);
  687.          return $this->get($varName);
  688.       }
  689.    }
  690.    
  691.    //-------------------------   build routes
  692.    
  693.    protected function getRoute($s, $param='') {
  694.    
  695.       $route = $this->_routes[$s];
  696.      
  697.       //$this->_w(array('routeName'=>$s, 'route'=>$route),__METHOD__);
  698.      
  699.       if (is_array($param)) {
  700.      
  701.          $zpar = array();
  702.          foreach ($param as $key=>$value) {
  703.          
  704.             $zpar[] = & $param[$key];
  705.          }
  706.          array_unshift($zpar, $route);
  707.          
  708.          $route = call_user_func_array('sprintf', $zpar);
  709.          }
  710.       else
  711.          $route = sprintf($route, $param);
  712.      
  713.       return $_SERVER["PHP_SELF"].'?controller='.$this->_controller.'&'.$route;
  714.    }
  715.    
  716.    //-------------------------   set variables
  717.    
  718.    public function set($name, $value) {
  719.      
  720.       $this->variables[$name] = $value;
  721.    }
  722.    
  723.    //-------------------------   get variables
  724.    
  725.    protected function get($name) {
  726.    
  727.       if (array_key_exists($name, $this->variables))
  728.      
  729.          return $this->variables[$name];
  730.       else
  731.          return false;
  732.    }
  733.    
  734.    //--------------   common rendering operations and filling blocks
  735.    
  736.     abstract protected function commonRender();
  737.     abstract protected function renderBlocks();
  738.    
  739.    //-------------------------   output view to template
  740.    
  741.    private function output($tmpl) {
  742.      
  743.       if ($tmpl=='')
  744.          $tmpl= $this->_stdtemplate;
  745.    
  746.       $c = get_class($this);
  747.       $c = strtolower(substr($c, 0, strpos($c,'View')));
  748.      
  749.       $blocks = array_values($this->_blocks);
  750.       array_unshift($blocks , $c);
  751.      
  752.       $s = str_replace (array('%viewid%','%header%','%content%','%sidebar%','%footer%'), $blocks, $tmpl);
  753.      
  754.       return $s;     
  755.    }
  756.    
  757.    //-------------------------   render view
  758.    
  759.    public function render($retblocks, $tmpl ) {
  760.    
  761.       $this->commonRender();
  762.    
  763.       if (method_exists($this, $this->_action))
  764.          call_user_func(array($this, $this->_action));
  765.          
  766.       $this->renderBlocks();
  767.      
  768.    
  769.       if ($retblocks)   {
  770.      
  771.          $c = get_class($this);
  772.          $pref = substr($c,0, strpos($c,'View'));
  773.          $prefixf = create_function('$a', 'return "'.$pref.'_".$a;');
  774.          return
  775.             array_combine(
  776.                    array_map($prefixf, array_keys($this->_blocks)),
  777.                    array_values($this->_blocks));
  778.          }       
  779.       else
  780.          return $this->output($tmpl);    
  781.    }
  782. }
  783.  
  784. //----------------------------------------------
  785. //                  DBModel
  786. //----------------------------------------------
  787. class DBModel {
  788.    
  789.    protected $_db;
  790.    protected $_table='';
  791.    protected $_idfield='';
  792.    protected $fields = array(); // fn, ft
  793.    
  794.    protected $filter = '';
  795.    protected $order = '';
  796.    
  797.    //---------------------------- debug information
  798.    protected function _w($info, $method) {
  799.    
  800.       $className = get_class($this);
  801.       Debugger::writeInfo($info, $className, $method);
  802.    }
  803.    //------------------------------ constructor
  804.    
  805.    protected function __construct() {
  806.  
  807.       $this->_db = DBConn::get();
  808.    }
  809.    
  810.    //------------------------------ check errors
  811.    
  812.    private function checkResult($result, $err, $sql='') {
  813.    
  814.       if ($result===false)
  815.          throw new Exception ('db error '.$err.'<br/>sql: '.$sql, 30044);
  816.    }
  817.    //------------------------------ get single record from model table
  818.    
  819.    protected function getRecordById($id) {
  820.    
  821.        //$stmt = $this->_db->prepare(
  822.        //   'select * from '.$this->_table.' where '.$this->_idfield.'=?');      
  823.        //$stmt->bind_param('i', $id);
  824.                
  825.        $sql =  'select * from '.$this->_table.
  826.        ' where '.$this->_idfield.'='. $this->_db->real_escape_string($id);
  827.                                          
  828.        $result = $this->_db->query($sql);
  829.        $this->checkResult($result, $this->_db->error, $sql);
  830.        
  831.        $row = $result->fetch_array(MYSQLI_ASSOC);
  832.        
  833.        $result->close();
  834.      
  835.        return $row;
  836.     }
  837.  
  838.    //------------------------------ get N records from model table
  839.    
  840.    protected function getNRecords($start, $num) {
  841.      
  842.      
  843.       $sql =  'select * from '.$this->_table.' '.$this->filter.' '.$this->order;
  844.       $result = $this->_db->query($sql);
  845.      
  846.       $this->checkResult($result, $this->_db->error, $sql);
  847.          
  848.       $result->data_seek($start);
  849.      
  850.       $i=0;
  851.       $ret = array();
  852.       while (($row = $result->fetch_assoc()) && ($i<$num)) {
  853.      
  854.          $ret[] = $row;
  855.          $i++;
  856.       }
  857.       $result->close();
  858.       //$this->_w($ret, __METHOD__);
  859.       return $ret;
  860.    }
  861.  
  862.    //------------------------------ get number of records in model table
  863.    
  864.    protected function getNumRecs() {
  865.    
  866.       $sql = 'select count(*) from '.$this->_table;
  867.       $result = $this->_db->query($sql);
  868.      
  869.       $this->checkResult($result, $this->_db->error, $sql);
  870.      
  871.       $inf = $result->fetch_row();
  872.       $result->close();
  873.      
  874.       return $inf[0];
  875.      
  876.    }
  877.    
  878.    //------------------------------ inserting and updating records
  879.    
  880.    protected function processRecord($type='update',$id,$values) {
  881.      
  882.       $flds = array();
  883.       $types = array();
  884.       $invars = array();
  885.      
  886.       $func = create_function ('$a', 'return $a["fn"];');
  887.       $func4 = create_function('$a','return $a."=?";');
  888.      
  889.       //$this->_w($values,__METHOD__);
  890.      
  891.       $sarr = array_map($func, $this->fields);
  892.      
  893.       foreach ($values as $key=>$value) {
  894.          
  895.          $flds[] = $key;
  896.          $invars[] = & $values[$key];
  897.            
  898.          $types[] = $this->fields[array_search($key, $sarr)]['ft'];
  899.       }
  900.       //--------------------------
  901.       if ($type=='insert') {
  902.      
  903.          $flds_s = implode(',',$flds);
  904.          $valpos = implode(',' , array_fill(0, count($flds),'?'));
  905.          
  906.       } else {
  907.          
  908.          $fld_s = implode(',' , array_map($func4, $flds));
  909.       }
  910.       //--------------------------
  911.       $types_s = implode('',$types);
  912.      
  913.       array_unshift($invars, $types_s);
  914.      
  915.       //---------------------------
  916.       if ($type=='insert')
  917.          $sql = 'insert into '.$this->_table.'('.$flds_s.') values ('.$valpos.')';
  918.       else
  919.          $sql = 'update '.$this->_table.' set '.$fld_s.
  920.           ' where '.$this->_idfield.'='.$this->_db->real_escape_string($id);
  921.      
  922.       //---------------------------
  923.       $stmt = $this->_db->prepare ($sql);
  924.    
  925.      
  926.       call_user_func_array(array($stmt,'bind_param'), $invars);
  927.      
  928.       $rez = $stmt->execute();
  929.       $this->checkResult($rez, $stmt->error, $sql);
  930.      
  931.       $rid = ($type=='insert') ? $stmt->insert_id : $stmt->affected_rows ;
  932.       $stmt->close();
  933.      
  934.       return($rid);
  935.  
  936.    }
  937.    //-------------------------------------- insert record  
  938.    protected function insertRecord($values) {
  939.    
  940.       $rid = $this->processRecord ('insert', 0, $values);    
  941.       return array('message'=>'record successfully inserted. record id: '.$rid, 'rid'=>$rid);
  942.    }
  943.    
  944.    //-------------------------------------- update record
  945.    
  946.    protected function updateRecord($id, $values) {
  947.    
  948.       $affected_rows = $this->processRecord('update', $id, $values);
  949.       return 'record successfully updated. affected rows: '.$affected_rows;
  950.    }
  951.    
  952.    //--------------------------------------- delete record
  953.    protected function deleteRecord($id) {
  954.    
  955.       $sql = 'delete from '.$this->_table.' where '.$this->_idfield.'=?';
  956.       $stmt = $this->_db->prepare($sql);
  957.      
  958.       $stmt->bind_param('i', $id);
  959.      
  960.       $rez = $stmt->execute();
  961.       $this->checkResult($rez, $stmt->error, $sql);
  962.      
  963.       $affected_rows = $stmt->affected_rows;
  964.       $stmt->close();
  965.      
  966.       return ('record successfully deleted. affected rows: '.$affected_rows);
  967.    }
  968. }
  969.  
  970. //----------------------------------------------
  971. //                  Model
  972. //----------------------------------------------
  973. abstract class Model extends DBModel {
  974.    
  975.    protected $_postvars = array();
  976.    private $_autovars = array();
  977.    
  978.    public $rec_per_page=3;
  979.    
  980.    //--------------------------------   get post vars
  981.    private function getPostVars() {
  982.      
  983.       foreach ($_POST as $key=>$val) {
  984.          foreach ($this->_postvars as $pkey=>$pval) {
  985.          
  986.             if ($key==$pkey) {
  987.                $this->_postvars[$pkey] = $val;
  988.             }
  989.          }
  990.       }
  991.    }  
  992.    //--------------------------------   set auto vars
  993.    
  994.    abstract protected function setAutoVars();
  995.    
  996.    //--------------------------------   prepare to write to database
  997.    private function prepareInfo() {
  998.      
  999.       $this->getPostVars();
  1000.      
  1001.       //$this->_w($this->_postvars,__METHOD__);
  1002.       $this->setAutoVars();
  1003.      
  1004.       return  array_merge($this->_postvars, $this->_autovars);
  1005.    }
  1006.    
  1007.    //--------------------------------   constructor
  1008.    public function __construct() {
  1009.    
  1010.       parent::__construct();  
  1011.    }  
  1012.    //--------------------------------   set properties handler
  1013.    public function __set($name, $value) {
  1014.      
  1015.       if (substr($name,0,3)==='a__') {
  1016.      
  1017.          $varName = substr($name,3);
  1018.          $this->_autovars[$varName] = $value;
  1019.       }
  1020.    }      
  1021.    //--------------------------------   get single item
  1022.    
  1023.    public function getSingle($record_id) {
  1024.    
  1025.       return $this->getRecordById($record_id);
  1026.    }
  1027.    //--------------------------------   get page
  1028.    
  1029.    public function getPage($page_id=0) {
  1030.  
  1031.       if (!is_numeric($page_id))
  1032.          $page_id = 0;
  1033.        
  1034.       return $this->getNRecords($page_id * $this->rec_per_page, $this->rec_per_page);
  1035.    }
  1036.    //--------------------------------   get number of pages
  1037.    public function getNumPages() {
  1038.      
  1039.       $nrecs = $this->getNumRecs();
  1040.      
  1041.       return (ceil($nrecs/$this->rec_per_page));
  1042.    }  
  1043.    //--------------------------------   insert item
  1044.    public function insertItem() {
  1045.          
  1046.       return $this->insertRecord($this->prepareInfo());
  1047.    }
  1048.    //--------------------------------   update item
  1049.    public function updateItem($id) {
  1050.    
  1051.      
  1052.       return $this->updateRecord($id, $this->prepareInfo());
  1053.    }
  1054.    //--------------------------------   delete item
  1055.    public function deleteItem($id) {
  1056.    
  1057.       return $this->deleteRecord($id);
  1058.    }
  1059. }    
  1060.  
  1061.  
  1062. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement