Ultra-Simple PHPMVC

Source: Internet
Author: User
Tags autoload
Native PHP syntax to render the page while providing widget functionality
  1. /**
  2. * Get and Set configuration parameters support Batch Definition
  3. * If $key is an associative array, the configuration is written as K-v
  4. * If $key is a numeric index array, the corresponding configuration array is returned
  5. * @param string|array $key Configuration variables
  6. * @param array|null $value configuration values
  7. * @return Array|null
  8. */
  9. function C ($key, $value =null) {
  10. Static $_config = Array ();
  11. $args = Func_num_args ();
  12. if ($args = = 1) {
  13. if (is_string ($key)) {//If the key passed in is a string
  14. return Isset ($_config[$key])? $_config[$key]:null;
  15. }
  16. if (Is_array ($key)) {
  17. if (Array_keys ($key)!== range (0, COUNT ($key)-1)) {//If the key passed in is an associative array
  18. $_config = Array_merge ($_config, $key);
  19. }else{
  20. $ret = Array ();
  21. foreach ($key as $k) {
  22. $ret [$k] = Isset ($_config[$k])? $_config[$k]:null;
  23. }
  24. return $ret;
  25. }
  26. }
  27. }else{
  28. if (is_string ($key)) {
  29. $_config[$key] = $value;
  30. }else{
  31. Halt (' Incoming parameter is incorrect ');
  32. }
  33. }
  34. return null;
  35. }
  36. /**
  37. * Call Widget
  38. * @param string $name widget name
  39. * @param array $data The list of variables passed to the widget, key is the variable name, value is the variable
  40. * @return void
  41. */
  42. function W ($name, $data = Array ()) {
  43. $fullName = $name. ' Widgets ';
  44. if (!class_exists ($fullName)) {
  45. Halt (' Widgets '. $name. ' does not exist ');
  46. }
  47. $widget = new $fullName ();
  48. $widget->invoke ($data);
  49. }
  50. /**
  51. * Terminate program Run
  52. * @param string $str termination reason
  53. * @param BOOL $display Whether the call stack is displayed and not displayed by default
  54. * @return void
  55. */
  56. function Halt ($STR, $display =false) {
  57. Log::fatal ($str. ' Debug_backtrace: '. Var_export (Debug_backtrace (), true));
  58. Header ("content-type:text/html; Charset=utf-8 ");
  59. if ($display) {
  60. echo "
    ";
  61. Debug_print_backtrace ();
  62. echo "
  63. ";
  64. }
  65. Echo $str;
  66. Exit
  67. }
  68. /**
  69. * Get DB instance
  70. * @return DB
  71. */
  72. function M () {
  73. $dbConf = C (Array (' Db_host ', ' db_port ', ' db_user ', ' db_pwd ', ' db_name ', ' db_charset '));
  74. Return db::getinstance ($dbConf);
  75. }
  76. /**
  77. * If the file exists, include in
  78. * @param string $path file path
  79. * @return void
  80. */
  81. function Includeifexist ($path) {
  82. if (file_exists ($path)) {
  83. Include $path;
  84. }
  85. }
  86. /**
  87. * General Control class
  88. */
  89. Class Singlephp {
  90. /**
  91. * Controller
  92. * @var String
  93. */
  94. Private $c;
  95. /**
  96. * Action
  97. * @var String
  98. */
  99. Private $a;
  100. /**
  101. * Single case
  102. * @var singlephp
  103. */
  104. private static $_instance;
  105. /**
  106. * Constructor, initialize configuration
  107. * @param array $conf
  108. */
  109. Private function __construct ($conf) {
  110. C ($conf);
  111. }
  112. Private Function __clone () {}
  113. /**
  114. * Get a single case
  115. * @param array $conf
  116. * @return singlephp
  117. */
  118. public static function getinstance ($conf) {
  119. if (! ( Self::$_instance instanceof Self)) {
  120. Self::$_instance = new self ($conf);
  121. }
  122. return self::$_instance;
  123. }
  124. /**
  125. * Run an Application instance
  126. * @access Public
  127. * @return void
  128. */
  129. Public Function run () {
  130. if (C (' use_session ') = = True) {
  131. Session_Start ();
  132. }
  133. C (' App_full_path ', GETCWD (). ' /'. C (' App_path '). ' /');
  134. Includeifexist (C (' App_full_path '). ' /common.php ');
  135. $pathMod = C (' Path_mod ');
  136. $pathMod = Empty ($pathMod)? ' NORMAL ': $pathMod;
  137. Spl_autoload_register (Array (' singlephp ', ' autoload '));
  138. if (strcmp (Strtoupper ($pathMod), ' NORMAL ') = = = 0 | |!isset ($_server[' path_info ')) {
  139. $this->c = isset ($_get[' C ') "$_get[' C ']: ' Index ';
  140. $this->a = isset ($_get[' a ') "$_get[' A ']: ' Index ';
  141. }else{
  142. $pathInfo = isset ($_server[' path_info ') "$_server[' Path_info ']: ';
  143. $PATHINFOARR = explode ('/', trim ($pathInfo, '/'));
  144. if (isset ($pathInfoArr [0]) && $pathInfoArr [0]!== ') {
  145. $this->c = $pathInfoArr [0];
  146. }else{
  147. $this->c = ' Index ';
  148. }
  149. if (Isset ($PATHINFOARR [1])) {
  150. $this->a = $PATHINFOARR [1];
  151. }else{
  152. $this->a = ' Index ';
  153. }
  154. }
  155. if (!class_exists ($this->c. ' Controller ')) {
  156. Halt (' controller '. $this->c. ' Not present ');
  157. }
  158. $controllerClass = $this->c. ' Controller ';
  159. $controller = new $controllerClass ();
  160. if (!method_exists ($controller, $this->a. ' Action ')) {
  161. Halt (' method '. $this->a. ' Not present ');
  162. }
  163. Call_user_func (Array ($controller, $this->a. ' Action '));
  164. }
  165. /**
  166. * Auto Load function
  167. * @param string $class class name
  168. */
  169. public static function AutoLoad ($class) {
  170. if (substr ($class, -10) = = ' Controller ') {
  171. Includeifexist (C (' App_full_path '). ' /controller/'. $class. Class.php ');
  172. }elseif (substr ($class, -6) = = ' Widget ') {
  173. Includeifexist (C (' App_full_path '). ' /widget/'. $class. Class.php ');
  174. }else{
  175. Includeifexist (C (' App_full_path '). ' /lib/'. $class. Class.php ');
  176. }
  177. }
  178. }
  179. /**
  180. * Controller class
  181. */
  182. Class Controller {
  183. /**
  184. * View Instance
  185. * @var View
  186. */
  187. Private $_view;
  188. /**
  189. * constructor, initialize view instance, call Hook
  190. */
  191. Public Function __construct () {
  192. $this->_view = new View ();
  193. $this->_init ();
  194. }
  195. /**
  196. * Front Hook
  197. */
  198. protected function _init () {}
  199. /**
  200. * Render template and output
  201. * @param null|string $tpl template file path
  202. * The parameter is relative to the app/view/file and does not contain a suffix name, such as Index/index
  203. * If the parameter is empty, the $controller/$action is used by default. php
  204. * If the parameter does not contain "/", the $controller/is used by default $tpl
  205. * @return void
  206. */
  207. protected function display ($TPL = ") {
  208. if ($tpl = = =) {
  209. $trace = Debug_backtrace ();
  210. $controller = substr ($trace [1][' class '], 0,-10);
  211. $action = substr ($trace [1][' function '], 0,-6);
  212. $TPL = $controller. '/' . $action;
  213. }elseif (Strpos ($TPL, '/') = = = = False) {
  214. $trace = Debug_backtrace ();
  215. $controller = substr ($trace [1][' class '], 0,-10);
  216. $TPL = $controller. '/' . $TPL;
  217. }
  218. $this->_view->display ($TPL);
  219. }
  220. /**
  221. * Set a template variable for the view engine
  222. * @param string $name The name of the variable to be used in the template
  223. * @param the value corresponding to the variable name in the mixed $value template
  224. * @return void
  225. */
  226. protected function Assign ($name, $value) {
  227. $this->_view->assign ($name, $value);
  228. }
  229. /**
  230. * Output data in JSON format to the browser and stop code execution
  231. * @param array $data The data to be output
  232. */
  233. protected function Ajaxreturn ($data) {
  234. echo Json_encode ($data);
  235. Exit
  236. }
  237. /**
  238. * Redirect to the specified URL
  239. * @param string $url the URL to jump
  240. * @param void
  241. */
  242. protected function Redirect ($url) {
  243. Header ("Location: $url");
  244. Exit
  245. }
  246. }
  247. /**
  248. * View class
  249. */
  250. Class View {
  251. /**
  252. * View File directory
  253. * @var String
  254. */
  255. Private $_tpldir;
  256. /**
  257. * View File path
  258. * @var String
  259. */
  260. Private $_viewpath;
  261. /**
  262. * View variable List
  263. * @var Array
  264. */
  265. Private $_data = Array ();
  266. /**
  267. * List of variables to be used for tplinclude
  268. * @var Array
  269. */
  270. private static $tmpData;
  271. /**
  272. * @param string $tplDir
  273. */
  274. Public function __construct ($tplDir = ") {
  275. if ($tplDir = = ") {
  276. $this->_tpldir = './'. C (' App_path '). ' /view/';
  277. }else{
  278. $this->_tpldir = $tplDir;
  279. }
  280. }
  281. /**
  282. * Set a template variable for the view engine
  283. * @param string $key The name of the variable to be used in the template
  284. * @param the value corresponding to the variable name in the mixed $value template
  285. * @return void
  286. */
  287. Public function assign ($key, $value) {
  288. $this->_data[$key] = $value;
  289. }
  290. /**
  291. * Render template and output
  292. * @param null|string $tplFile template file path, relative to the app/view/file, does not contain a suffix name, such as Index/index
  293. * @return void
  294. */
  295. Public function display ($tplFile) {
  296. $this->_viewpath = $this->_tpldir. $tplFile. '. php ';
  297. Unset ($tplFile);
  298. Extract ($this->_data);
  299. Include $this->_viewpath;
  300. }
  301. /**
  302. * Used to include other templates in the template file
  303. * @param string $path Path relative to the view directory
  304. * @param array $data The list of variables passed to the child template, key is the variable name, value is the variable
  305. * @return void
  306. */
  307. public static function Tplinclude ($path, $data =array ()) {
  308. Self:: $tmpData = Array (
  309. ' path ' = = C (' App_full_path '). '/view/'. $path. '. php ',
  310. ' Data ' = $data,
  311. );
  312. Unset ($path);
  313. Unset ($data);
  314. Extract (self:: $tmpData [' data ']);
  315. Include self:: $tmpData [' path '];
  316. }
  317. }
  318. /**
  319. * Widget class
  320. * Inherit this class when used, override the Invoke method, and invoke the display in the Invoke method
  321. */
  322. Class Widget {
  323. /**
  324. * View Instance
  325. * @var View
  326. */
  327. protected $_view;
  328. /**
  329. * Widget Name
  330. * @var String
  331. */
  332. protected $_widgetname;
  333. /**
  334. * constructor, Initialize view instance
  335. */
  336. Public Function __construct () {
  337. $this->_widgetname = Get_class ($this);
  338. $dir = C (' App_full_path '). '/widget/tpl/';
  339. $this->_view = new View ($DIR);
  340. }
  341. /**
  342. * Processing Logic
  343. * @param mixed $data parameters
  344. */
  345. Public function Invoke ($data) {}
  346. /**
  347. * Render Template
  348. * @param string $tpl template path, if blank, use class name as template
  349. */
  350. protected function display ($TPL = ") {
  351. if ($tpl = = ") {
  352. $TPL = $this->_widgetname;
  353. }
  354. $this->_view->display ($TPL);
  355. }
  356. /**
  357. * Set a template variable for the view engine
  358. * @param string $name The name of the variable to be used in the template
  359. * @param the value corresponding to the variable name in the mixed $value template
  360. * @return void
  361. */
  362. protected function Assign ($name, $value) {
  363. $this->_view->assign ($name, $value);
  364. }
  365. }
  366. /**
  367. * Database Operation class
  368. * How to use:
  369. * Db::getinstance ($conf)->query (' SELECT * from table ');
  370. * Where $conf is an associative array, it needs to contain the following key:
  371. * Db_host Db_user db_pwd db_name
  372. * Ports and encodings can be specified using Db_port and Db_charset, default 3306 and UTF8
  373. */
  374. Class DB {
  375. /**
  376. * Database Link
  377. * @var Resource
  378. */
  379. Private $_db;
  380. /**
  381. * Save Last SQL
  382. * @var String
  383. */
  384. Private $_lastsql;
  385. /**
  386. * The number of rows affected by the last SQL statement
  387. * @var int
  388. */
  389. Private $_rows;
  390. /**
  391. * Last SQL Execution error
  392. * @var String
  393. */
  394. Private $_error;
  395. /**
  396. * Instance Array
  397. * @var Array
  398. */
  399. private static $_instance = Array ();
  400. /**
  401. * Constructor function
  402. * @param array $dbConf configuration
  403. */
  404. Private function __construct ($dbConf) {
  405. if (!isset ($dbConf [' Db_charset '])) {
  406. $dbConf [' db_charset '] = ' UTF8 ';
  407. }
  408. $this->_db = mysql_connect ($dbConf [' db_host ']. ': ' $dbConf [' Db_port '], $dbConf [' Db_user '], $dbConf [' db_pwd ']);
  409. if ($this->_db = = = False) {
  410. Halt (Mysql_error ());
  411. }
  412. $selectDb = mysql_select_db ($dbConf [' db_name '], $this->_db);
  413. if ($selectDb = = = False) {
  414. Halt (Mysql_error ());
  415. }
  416. Mysql_set_charset ($dbConf [' db_charset ']);
  417. }
  418. Private Function __clone () {}
  419. /**
  420. * Get DB Class
  421. * @param array $dbConf configuration
  422. * @return DB
  423. */
  424. static public Function getinstance ($dbConf) {
  425. if (!isset ($dbConf [' Db_port '])) {
  426. $dbConf [' db_port '] = ' 3306 ';
  427. }
  428. $key = $dbConf [' db_host ']. ': ' $dbConf [' db_port '];
  429. if (!isset (self::$_instance[$key]) | |! ( self::$_instance[$key] instanceof self)) {
  430. self::$_instance[$key] = new self ($dbConf);
  431. }
  432. return self::$_instance[$key];
  433. }
  434. /**
  435. * Escape string
  436. * @param string $str to be escaped
  437. * Strings escaped @return string
  438. */
  439. Public function Escape ($STR) {
  440. Return mysql_real_escape_string ($STR, $this->_db);
  441. }
  442. /**
  443. * Query, for SELECT statements
  444. * @param string $sql sql to query
  445. * @return Bool|array query successfully returned the corresponding array, failed to return false
  446. */
  447. Public Function Query ($sql) {
  448. $this->_rows = 0;
  449. $this->_error = ";
  450. $this->_lastsql = $sql;
  451. $this->logsql ();
  452. $res = mysql_query ($sql, $this->_db);
  453. if ($res = = = False) {
  454. $this->_error = mysql_error ($this->_db);
  455. $this->logerror ();
  456. return false;
  457. }else{
  458. $this->_rows = mysql_num_rows ($res);
  459. $result = Array ();
  460. if ($this->_rows >0) {
  461. while ($row = Mysql_fetch_array ($res, Mysql_assoc)) {
  462. $result [] = $row;
  463. }
  464. Mysql_data_seek ($res, 0);
  465. }
  466. return $result;
  467. }
  468. }
  469. /**
  470. * Query, for INSERT/UPDATE/DELETE statements
  471. * @param string $sql sql to query
  472. * @return Bool|int Query successfully returns the number of records affected, failure returns false
  473. */
  474. Public function Execute ($sql) {
  475. $this->_rows = 0;
  476. $this->_error = ";
  477. $this->_lastsql = $sql;
  478. $this->logsql ();
  479. $result = mysql_query ($sql, $this->_db);
  480. if (false = = = $result) {
  481. $this->_error = mysql_error ($this->_db);
  482. $this->logerror ();
  483. return false;
  484. } else {
  485. $this->_rows = mysql_affected_rows ($this->_db);
  486. return $this->_rows;
  487. }
  488. }
  489. /**
  490. * Get the number of records affected by the last query
  491. * Number of records affected by @return int
  492. */
  493. Public Function getRows () {
  494. return $this->_rows;
  495. }
  496. /**
  497. * Gets the self-increment ID generated after the last insert
  498. * @return int self-increment ID
  499. */
  500. Public Function Getinsertid () {
  501. Return mysql_insert_id ($this->_db);
  502. }
  503. /**
  504. * Get SQL for the last query
  505. * @return String sql
  506. */
  507. Public Function Getlastsql () {
  508. return $this->_lastsql;
  509. }
  510. /**
  511. * Get error information for the last query
  512. * @return String Error message
  513. */
  514. Public Function GetError () {
  515. return $this->_error;
  516. }
  517. /**
  518. * Log SQL to file
  519. */
  520. Private Function Logsql () {
  521. Log::sql ($this->_lastsql);
  522. }
  523. /**
  524. * Record error log to file
  525. */
  526. Private Function LogError () {
  527. $str = ' [SQL ERR] '. $this->_error. ' SQL: '. $this->_lastsql;
  528. Log::warn ($STR);
  529. }
  530. }
  531. /**
  532. * Log Class
  533. * How to use: Log::fatal (' Error msg ');
  534. * Save path to App/log, store by day
  535. * Fatal and warning will be recorded in the. log.wf file
  536. */
  537. Class log{
  538. /**
  539. * Log, support SAE environment
  540. * @param string $msg log content
  541. * @param string $level log level
  542. * @param bool $WF is an error log
  543. */
  544. public static function Write ($msg, $level = ' DEBUG ', $wf =false) {
  545. if (function_exists (' Sae_debug ')) {//If it is SAE, use the Sae_debug function to log
  546. $msg = "[{$level}]". $msg;
  547. Sae_set_display_errors (FALSE);
  548. Sae_debug (Trim ($msg));
  549. Sae_set_display_errors (TRUE);
  550. }else{
  551. $msg = Date (' [y-m-d h:i:s] '). " [{$level}] ". $msg." \ r \ n ";
  552. $logPath = C (' App_full_path '). ' /log/'. Date (' Ymd '). Log ';
  553. if ($WF) {
  554. $logPath. = '. WF ';
  555. }
  556. File_put_contents ($logPath, $msg, file_append);
  557. }
  558. }
  559. /**
  560. * Print Fatal Log
  561. * @param string $msg log information
  562. */
  563. public static function Fatal ($MSG) {
  564. Self::write ($msg, ' FATAL ', true);
  565. }
  566. /**
  567. * Print Warning Log
  568. * @param string $msg log information
  569. */
  570. public static function warn ($msg) {
  571. Self::write ($msg, ' WARN ', true);
  572. }
  573. /**
  574. * Print Notice Log
  575. * @param string $msg log information
  576. */
  577. public static function notice ($msg) {
  578. Self::write ($msg, ' NOTICE ');
  579. }
  580. /**
  581. * Print Debug Log
  582. * @param string $msg log information
  583. */
  584. public static function debug ($msg) {
  585. Self::write ($msg, ' DEBUG ');
  586. }
  587. /**
  588. * Print SQL Log
  589. * @param string $msg log information
  590. */
  591. public static function SQL ($MSG) {
  592. Self::write ($msg, ' SQL ');
  593. }
  594. }
  595. /**
  596. * Extexception class, record additional exception information
  597. */
  598. Class Extexception extends exception{
  599. /**
  600. * @var Array
  601. */
  602. protected $extra;
  603. /**
  604. * @param string $message
  605. * @param array $extra
  606. * @param int $code
  607. * @param null $previous
  608. */
  609. Public function __construct ($message = "", $extra = Array (), $code = 0, $previous = null) {
  610. $this->extra = $extra;
  611. Parent::__construct ($message, $code, $previous);
  612. }
  613. /**
  614. * Get additional exception information
  615. * @return Array
  616. */
  617. Public Function Getextra () {
  618. return $this->extra;
  619. }
  620. }
Copy Code
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.