Advertisement
terorama

mvcnew / base.inc.php

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