Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- //----------------------------------------------
- // BootStrap
- //----------------------------------------------
- define('DB_HOST','');
- define('DB_NAME','');
- define('DB_USER','');
- define('DB_PASSWORD','');
- DBConn::set(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
- //-------------------------------------
- $controller = $_GET['controller'];
- $action = $_GET['action'];
- $controllerName = $controller;
- $controller = ucwords($controller);
- $model = rtrim($controller,'s');
- $view = $controller.'View';
- $controller .= 'Controller';
- $dispatch = new $controller($model, $view, $controllerName, $action);
- //----------------------------
- $dispatch->dispatch();
- //----------------------------
- $vblocks = $dispatch->render();
- ?>
- <html><head><title>test mvc page - <?php echo $vblocks['header']; ?></title></head>
- <body>
- <div id="container">
- <div id="header">
- <h1><?php echo $vblocks['header'];?></h1>
- </div>
- <div id="content">
- <?php echo $vblocks['content']; ?>
- </div>
- <div id="sidebar">
- <?php echo $vblocks['sidebar']; ?>
- </div>
- <div id="footer">
- <?php echo $vblocks['footer']; ?>
- </div>
- </body>
- </html>
- <?php
- //----------------------------------------------
- // base classes
- //----------------------------------------------
- class DBConn {
- private static $_db=0;
- private static $DB_HOST;
- private static $DB_USER;
- private static $DB_PASSWORD;
- private static $DB_NAME;
- //----------------------------------
- public static function connect() {
- self::$_db = @new mysqli (self::$DB_HOST, self::$DB_USER, self::$DB_PASSWORD, self::$DB_NAME );
- if (self::$_db->connect_errno) {
- throw new Exception('connection error '.self::$_db->connect_error);
- }
- }
- //----------------------------------
- public static function set($DB_HOST, $DB_USER, $DB_PASSWORD, $DB_NAME) {
- self::$DB_HOST = $DB_HOST;
- self::$DB_USER = $DB_USER;
- self::$DB_PASSWORD = $DB_PASSWORD;
- self::$DB_NAME = $DB_NAME;
- }
- //----------------------------------
- public static function get() {
- if (self::$_db==0) {
- self::connect();
- }
- return self::$_db;
- }
- }
- //----------------------------------------------
- // Controller
- //----------------------------------------------
- abstract class Controller {
- protected $_model;
- protected $_controller;
- protected $_action;
- protected $_view;
- protected $_routes;
- private $_params=array();
- //---------------------------- collect session and input parameters
- private function getSessionParams() {
- foreach ($_SESSION as $key=>$val) {
- foreach ($this->_params as $pkey=>$pval) {
- if ($key==$pkey) {
- $this->_params[$pkey]=$_SESSION[$key];
- }
- }
- }
- }
- //--------------------------------
- private function getInputParams() {
- foreach ($_REQUEST as $key=>$val) {
- foreach ($this->_params as $pkey=>$pval) {
- if ($key==$pkey) {
- $this->_params[$pkey]=$_REQUEST[$key];
- $_SESSION[$pkey] = $this->_params[$pkey];
- }
- }
- }
- }
- //---------------------------------- declare expected GET parameters
- abstract protected function declareParams();
- //--------------------------------get parameters
- private function getParams() {
- $this->getSessionParams();
- $this->getInputParams();
- }
- //---------------------------------------init
- public function __construct($model, $view, $controller, $action) {
- $this->_controller = $controller;
- $this->_model = $model;
- $this->_action = $action;
- $this->_view = $view;
- $this->$model = & new $model;
- $this->$view = & new $view($action, $controller, $this->_routes);
- //-----------------params
- $this->declareParams();
- $this->getParams();
- }
- //---------------------------------- properties get handler
- public function __get($name) {
- if (substr($name,0,3)=='p__') {
- $paramName = substr($name,3);
- if (array_key_exists($paramName, $this->_params))
- return $this->_params[$paramName];
- else
- return false;
- }
- }
- //---------------------------------- common dispatching operations
- abstract protected function commonDispatch();
- //---------------------------------- dispatch current action
- public function dispatch() {
- $this->commonDispatch();
- if ((int)method_exists($dispatch, $this->_action)) {
- call_user_func (array($dispatch, $this->_action));
- }
- }
- //--------------------------------- set view variable
- protected function set($name, $value) {
- $this->$view->set($name, $value)
- }
- //--------------------------------- set block of view variables
- protected function setAll($el) {
- foreach ($el as $key=>$value) {
- $this->set($key,$value);
- }
- }
- //---------------------------- render view
- function render() {
- return $this->$view->render();
- }
- }
- //----------------------------------------------
- // View
- //----------------------------------------------
- abstract class View {
- protected $variables = array();
- protected $_action;
- protected $_controller;
- private $_routes;
- protected $_blocks =array('header','content','sidebar','footer');
- //------------------------- constructor
- public function __construct($action, $controller, $routes) {
- $this->_action = $action;
- $this->_controller = $controller;
- $this->_routes = $routes;
- }
- //------------------------- func calls handler
- public function __call($name, $arguments) {
- if (substr($name, 0, 6 )=='route_') {
- $routeName = substr ($name, 6);
- return $this->getRoute($routeName, $arguments[0]);
- }
- }
- //----------------------------------- properties get handler
- public function __get($name) {
- if (substr($name,0,2)=='v_') {
- $varName = substr($name, 2);
- return $this->get($varName);
- }
- }
- //------------------------- build routes
- protected function getRoute($s, $param='') {
- $route = $this->_routes[$s];
- if (is_array($param))
- $zpar = array();
- foreach ($param as $key=>$value) {
- $zpar[] = & $param[$key];
- }
- array_unshift($zpar, $route);
- $route = call_user_func_array('sprintf', $zpar);
- else
- $route = sprintf($route, param);
- return $_SERVER["PHP_SELF"].'?controller='.$this->_controller.'&'.$route;
- }
- //------------------------- set variables
- public function set($name, $value) {
- $this->variables[$name] = $value;
- }
- //------------------------- get variables
- private function get($name) {
- if (array_key_exists($varName, $this->variables))
- return $this->variables[$name];
- else
- return false;
- }
- //-------------- common rendering operations and filling blocks
- abstract protected function commonRender();
- abstract protected function renderBlocks();
- //-------------------------
- public function render() {
- $this->commonRender();
- if (method_exists($this, $this->_action))
- call_user_func(array($this, $this->_action));
- $this->renderBlocks();
- return $_blocks;
- }
- }
- //----------------------------------------------
- // DBModel
- //----------------------------------------------
- class DBModel {
- private $_db;
- protected $_table='';
- protected $_idfield='';
- protected $fields = array(); // fn, ft
- protected $filter = '';
- protected $order = '';
- //------------------------------ constructor
- protected function __construct() {
- $this->_db = DBConn::get();
- }
- //------------------------------ check errors
- private function checkResult($result, $err) {
- if ($result===false)
- throw new Exception ('db error '.$err, 30044);
- }
- //------------------------------ get single record from model table
- protected function getRecordById($id) {
- $stmt = $this->_db->prepare(
- 'select * from '.$this->_table.' where '.$this->_idfield.'=?');
- $stmt->bind_param('i', $id);
- $result = $stmt->getResult();
- $this->checkResult($result, $stmt->error);
- $row = $result->fetch_array(MYSQLI_ASSOC);
- $result->close();
- $stmt->close();
- return $row;
- }
- //------------------------------ get N records from model table
- protected function getNRecords($start, $num) {
- $result = $this->_db->query(
- 'select * from '.$this->_table.' '.$this->filter.' '.$this->order);
- $this->checkResult($result, $this->_db->error);
- $result->data_seek($start);
- $i=0;
- $ret = array();
- while (($row = $result->fetch_assoc()) && ($i<$num)) {
- $ret[] = $row;
- $i++;
- }
- $result->close();
- return $ret;
- }
- //------------------------------ get number of records in model table
- protected function getNumRecs() {
- $result = $this->_db->query('select count(*) from '.$this->_table);
- $this->checkResult($result, $this->_db->error);
- $inf = $result->fetch_row();
- $result->close();
- return $inf[0];
- }
- //------------------------------ inserting and updating records
- protected function processRecord($type='update',$id,$values) {
- $flds = array();
- $types = array();
- $invars = array();
- $func = create_function ('$a', 'return $a["fn"];');
- $func4 = create_function('$a','return $a."=?"');
- $sarr = array_map($func, $this->fields);
- foreach ($values as $key=>$value) {
- $flds[] = $key;
- $invars[] = & $values[$key];
- $types[] = $this->fields[array_search($key, $sarr)]['ft'];
- }
- //--------------------------
- if ($type=='insert') {
- $flds_s = implode(',',$flds);
- $valpos = implode(','array_fill(0, count($flds),'?'));
- } else {
- $fld_s = implode(',' array_map($func4, $flds));
- }
- //--------------------------
- $types_s = implode('',$types);
- array_unshift($invars, $types_s);
- //---------------------------
- if ($type=='insert')
- $sql = 'insert into '.$this->_table.'('.$flds_s.') values ('.$valpos.')';
- else
- $sql = 'update '.$this->_table.' set '.$fld_s.
- ' where '.$this->_idfield.'='.mysql_real_escape_string($id);
- //---------------------------
- $stmt = $this->_db->prepare ($sql);
- call_user_func_array(array($stmt,'bind_param'), $invars);
- $rez = $stmt->execute();
- $this->checkResult($rez, $stmt->error);
- $rid = ($type=='insert') ? $stmt->insert_id : $stmt->affected_rows ;
- $stmt->close();
- return($rid);
- }
- //-------------------------------------- insert record
- protected function insertRecord($values) {
- $rid = $this->processRecord ('insert', 0, $values);
- return 'record successfully inserted. record id: '.$rid;
- }
- //-------------------------------------- update record
- protected function updateRecord($id, $values) {
- $affected_rows = $this->processRecord('update', $id, $values);
- return 'record successfully updated. affected rows: '.$affected_rows;
- }
- //--------------------------------------- delete record
- protected function deleteRecord($id) {
- $sql = 'delete from '.$this->_table.' where '.$this->idfield.'=?';
- $stmt = $this->_db->prepare($sql);
- $stmt->bind_param('i', $id);
- $rez = $stmt->execute();
- $this->checkResult($rez, $stmt->error);
- $affected_rows = $stmt->affected_rows;
- $stmt->close();
- return ('record successfully deleted. affected rows: '.$affected_rows);
- }
- }
- //----------------------------------------------
- // Model
- //----------------------------------------------
- class Model extends DBModel {
- private $_postvars = array();
- private $_autovars = array();
- public $rec_per_page=10;
- //-------------------------------- get post vars
- private function getPostVars() {
- foreach ($_POST as $key=>$val) {
- foreach ($this->_postvars as $pkey=>$pval) {
- if ($key==$pkey) {
- $this->_postvars[$pkey] = $val;
- }
- }
- }
- }
- //-------------------------------- set auto vars
- abstract protected function setAutoVars();
- //-------------------------------- prepare to write to database
- private function prepareInfo() {
- $this->getPostVars();
- $this->setAutoVars();
- return array_merge($this->_postvars, $this->_autovars);
- }
- //-------------------------------- constructor
- public function __construct() {
- parent::__construct();
- }
- //-------------------------------- set properties handler
- public function __set($name, $value) {
- if (substr($name,0,3)==='a__') {
- $varName = substr($name,3);
- $this->_autovars[$varName] = $value;
- }
- }
- //-------------------------------- get single item
- public function getSingle($record_id) {
- return $this->getRecordById($record_id);
- }
- //-------------------------------- get page
- public function getPage($page_id=0) {
- return $this->getNRecords($page_id * $this->rec_per_page, $this->rec_per_page);
- }
- //-------------------------------- get number of pages
- public function getNumPages() {
- $nrecs = $this->getNumRecs();
- return (ceil($nrecs/$this->rec_per_page));
- }
- //-------------------------------- insert item
- public function insertItem() {
- return $this->insertRecord($this->prepareInfo());
- }
- //-------------------------------- update item
- public function updateItem($id) {
- return $this->updateRecord($id, $this->prepareInfo());
- }
- //-------------------------------- delete item
- public function deleteItem($id) {
- return $this->deleteRecord($id);
- }
- }
- //----------------------------------------------
- // controllers
- //----------------------------------------------
- class QuestionsController extends Controller {
- protected $_routes = array (
- 'add_form' => 'action=add_form',
- 'insert' => 'action=insert',
- 'edit_form' => 'action=edit_form&qid=%d',
- 'update' => 'action=update&qid=%d',
- 'delete_form' => 'action=delete_form&qid=%d',
- 'delete' => 'action=delete&qid=%d',
- 'view_single' => 'action=view_single&qid=%d',
- 'view_page' => 'action=view_page&qpageid=%d');
- //----------------------------------- declare params
- protected function declareParams() {
- $this->_params = array('qid'=>'','qcategory'=>'','qpageid'=>'');
- }
- //----------------------------------- common dispatch
- protected function commonDispatch() {
- $this->set('nav_categoryname', $this->Question->getCategory($this->p__qcategory));
- $this->set('nav_numpages', $this->Question->getNumPages());
- $this->set('nav_pageid', $this->p__qpageid);
- }
- //--------------------------------- draw single record
- private function view_single() {
- $el = $this->Question->getSingle($this->p__qid);
- $this->setAll($el);
- }
- //-------------------------------- draw page
- private function view_page() {
- $els = $this->Question->getPage($this->p__qpageid);
- $this->set('items',$els);
- }
- //-------------------------------- draw add form
- private function add_form() {
- }
- //-------------------------------- insert record
- private function insert() {
- $this->set('message',$this->Question->insertItem());
- }
- //-------------------------------- draw edit form
- private function edit_form() {
- $el = $this->Question->getEntry($this->p__qid);
- $this->setAll($el);
- }
- //-------------------------------- update record
- private function update() {
- $this->set('message',$this->Question->updateItem($this->p__qid));
- }
- //-------------------------------- delete form
- private function delete_form() {
- }
- //-------------------------------- delete record
- private function delete() {
- $this->set('message',$this->Question->deleteItem($this->p__qid));
- }
- }
- //----------------------------------------------
- //----------------------------------------------
- //----------------------------------------------
- //----------------------------------------------
- // models
- //----------------------------------------------
- class Question extends Model {
- private $_table = 'questions';
- private $_idfield = 'qid';
- private $fields = array (
- array('fn'=>'qtitle', 'ft'=>'s'),
- array('fn'=>'qtext','ft'=>'s'),
- array('fn'=>'qcategory','ft'=>'i'),
- array('fn'=>'quser','ft'=>'i'),
- array('fn'=>'qdate','ft'=>'s'));
- private $_postvars = array ('qtitle', 'qtext', 'qcategory', 'quser');
- protected function setAutoVars() {
- $this->a__qdate = date('Y-m-d H:i:s');
- }
- }
- //----------------------------------------------
- // forms
- //----------------------------------------------
- class QuestionsForm extends stdForm {
- public function __construct($action, $flds) {
- parent::_construct( array('post','reset','cancel'),'default');
- $fset = $this->addFieldset('Question: ');
- $fset->addField('TEXT', 'qtitle', nzz($flds['qtitle'],''), 'Input question title');
- $fset->addField('TEXT', 'qcontent', nzz($flds['qcontent'],''),'Input question');
- $fset->addField('TEXT', 'qcategory', nzz($flds['qcategory'],''),'Input category');
- $fset->addField('TEXT', 'qauthor', nzz($flds['qauthor'],''),'Input your name');
- }
- }
- //----------------------------------------------
- // views
- //----------------------------------------------
- class QuestionsView extends View {
- private $bcblock = '';
- private $maincontent = '';
- private $navblock = '';
- private $catblock = '';
- private $editblock = '';
- private $infoblock = '';
- private $_addurl = ''
- //---------------------------- draw buttons for posts
- private function _drawButtons($record_id) {
- $s = '<div class="entryeditpanel">';
- $s .= '<div class="editbutton"><a href="'.$this->route_edit_form($record_id).'"></a></div>';
- $s .= '<div class="deletebutton"><a href="'.$this->route_delete_form($record_id).'"></a></div>';
- $s .= '</div>';
- return $s;
- }
- //---------------------------- draw page entry
- private function _drawPageEntry($item) {
- extract($item);
- $s ='';
- $s .='<div class="entrytitle"><a href="'.$this->route_view_single($qid).'">'.$qtitle.'</a></div>';
- $s .='<div class="entrycontent">'.$qcontent.'</div>';
- $s .='<div class="entrycategory">'.$qcategory.'</div>';
- $s .='<div class="entryuser">'.$quser.'</div>';
- $s .='<div class="entrydate">'.$qdate.'</div>';
- $s .= $this->_drawButtons($qid);
- return $s;
- }
- //---------------------------- draw page
- private function _drawPage() {
- $s = '<div class="page">'
- $items = $this->get('items');
- for ($i=0; $i<count($items); $i++) {
- $s .= $this->_drawPageEntry($items[$i]);
- }
- $s .= '</div>';
- return $s;
- }
- //---------------------------- draw single item
- private function _drawSingle() {
- $s = '<div class="content">'.$this->v_qcontent.'</div>';
- $s .= '<div class="category">'.$this->v_qcategory.'</div>';
- $s .= '<div class="author">'.$this->v_qauthor.'</div>';
- $s .= '<div class="date">'.$this->v_qdate.'</div>';
- return $s;
- }
- //---------------------------- draw form for adding or editing
- private function _drawForm($add_or_edit, $flds=null) {
- if ($add_or_edit == 'add')
- $action = $this->route_insert();
- else
- $action = $this->route_update($this->v_qid);
- $zform = new QuestionsForm($action, $flds);
- return $zform->draw();
- }
- //---------------------------- draw bread crumbs
- private function _drawBreadCrumbs() {
- return 'Category: '.$this->v_pos_category_name.' Page: '.$this->v_pos_page_id;
- }
- //---------------------------- draw navigation block
- private function _drawNavigation() {
- $s ='<div class="navigation"><ul>';
- for ($i=0; $i < $this->v_nav_numpages; $i++) {
- $s .='<li>';
- if ($i== $this->v_nav_pageid) {
- $s .= $i;
- } else {
- $s .= '<a href="'. $this->route_view_page($this->v_nav_pageid).'">'.$i.'</a>';
- }
- $s .= '</li>'
- }
- $s .= '</ul></div>';
- return $s;
- }
- //---------------------------- draw edit block
- private function _drawEditPanel() {
- $s = '<div class="editpanel">';
- $s .= '<div class="addbutton"><a href="'.$this->route_add_form().'"></a></div>';
- $s .= '<div class="editbutton"><a href="'.
- $this->route_edit_form($this->v_qid).'"></a></div>';
- $s .= '<div class="deletebutton"><a href="'.
- $this->route_delete_form($this->v_qid).'"></a></div>';
- $s .= '</div>';
- return $s;
- }
- //----------------------------- draw page and navigation
- private function _drawPageNav() {
- $this->maincontent = $this->_drawPage();
- $this->navblock = $this->_drawNavigation();
- }
- //---------------------------- draw common parts
- protected function commonRender() {
- $this->bcblock = $this->drawBreadCrumbs();
- }
- //---------------------------- put content into blocks
- protected function renderBlocks() {
- $this->_blocks['content'] = $this->bcblock.$this->infoblock.$this->maincontent;
- $this->_blocks['sidebar'] = $this->catblock;
- $this->_blocks['footer'] = $this->editblock. $this->navblock;
- }
- //-------------------------------------------
- // action handlers
- //-------------------------------------------
- //--------------------------- show single record
- private function view_single() {
- $this->_blocks['header'] = $this->v_qtitle;
- $this->maincontent = $this->_drawSingle();
- $this->editblock = $this->_drawEditPanel();
- }
- //--------------------------- show page
- private function view_page() {
- $this->_drawPageNav();
- }
- //---------------------------- show add form
- private function add_form() {
- $this->maincontent = $this->_drawForm('add');
- }
- //---------------------------- show insert record result
- private function insert() {
- $this->infoblock = $this->v_message;
- $this->_drawPageNav();
- }
- //---------------------------- show edit form
- private function edit_form() {
- $flds = array('qtitle'=> $this->v_qtitle,
- 'qcontent'=> $this->v_qcontent,
- 'qcategory'=> $this->v_qcategory,
- 'qauthor'=> $this->v_qauthor);
- $this->maincontent = $this->_drawForm('edit', $flds);
- }
- //---------------------------- show update record result
- private function update() {
- $this->infoblock = $this->v_message;
- $this->_drawPageNav();
- }
- //---------------------------- show delete form
- private function delete_form() {
- }
- //---------------------------- show delete record result
- private function delete() {
- $this->infoblock = $this->v_message;
- $this->_drawPageNav();
- }
- }
- //----------------------------------------------
- //----------------------------------------------
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement