search
HomeBackend DevelopmentPHP TutorialThis is the encapsulation of my MVC framework ActionController

This is the encapsulation of my MVC framework ActionController
  1. /*
  2. * MST_Library v3.1
  3. * @autohr Janpoem
  4. */
  5. if (!defined('IN_MST_CORE'))
  6. exit('MST_ActionController Can't be include single! ');
  7. if (!defined(MST_Core::LITE_MODE)) {
  8. MST_Core::import(array(
  9. 'MST/ActionController/Request',
  10. 'MST/ActionController/Router',
  11. ), MST_Core::P_LIB ;
  12. VIEW = ' view',
  13. TEXT = 'text',
  14. ACTION = 'action',
  15. WIDGET = 'widget',
  16. CUSTOM_VIEW = 'custom_view';
  17. private static
  18. $_request = null,
  19. $_instance = null,
  20. $_currentView = null;
  21. # @todo The processing here should be done after the controller is instantiated, dispatch should have a specific meaning
  22. final static public function dispatch(array $config = null, $beforeDispatch = null) {
  23. if (self ::$_instance == null) {
  24. $request = new MST_ActionController_Request($config['request']);
  25. $router = new MST_ActionController_Router($config['routes']);
  26. $router->routing($ request);
  27. $controller = $request['controller'];
  28. $controller = MST_String::camelize2($controller) . static::PF_CONTROLLER;
  29. if ($request['module'] != null) {
  30. $ module = $request['module'];
  31. if (strpos($module, '/') !== false)
  32. $module = str_replace('/', '_', $module);
  33. $controller = $ module . '_' . $controller;
  34. }
  35. if (is_callable($beforeDispatch)) {
  36. call_user_func_array($beforeDispatch, array($request, & $controller));
  37. }
  38. $GLOBALS['DATA_CACHE'][' request'] = & $request;
  39. if (!class_exists($controller))
  40. MST_Core::error(202, $controller);
  41. else
  42. self::$_instance = new $controller();
  43. }
  44. }
  45. public
  46. $layout = false,
  47. $format = 'html',
  48. $params = null,
  49. $autoLoadHelper = false;
  50. protected
  51. $comet = 0,
  52. $viewPath = null,
  53. $defaultRender = self:: VIEW;
  54. abstract public function application();
  55. private function __construct()
  56. {
  57. if ($this->comet ob_start();
  58. $this->params = & $GLOBALS ['DATA_CACHE']['request'];
  59. $this->viewPath = trim(
  60. $this->params['module'] . '/' . $this->params['controller'], '/');
  61. if ($this->application() !== self::NO_RENDER)
  62. $this->action($this->params['action']);
  63. }
  64. public function __destruct() {
  65. if (!defined(self::IS_RENDER) && self::$_currentView != null) {
  66. switch ($this->defaultRender) {
  67. case self::VIEW :
  68. case self:: TEXT :
  69. case self::ACTION :
  70. case self::WIDGET :
  71. #$this->defaultRender = $mode;
  72. break;
  73. default :
  74. $this->defaultRender = self::VIEW;
  75. }
  76. $this->render(
  77. $this->defaultRender,
  78. self::$_currentView
  79. );
  80. }
  81. if (self::$_instance != null)
  82. self::$_instance = null;
  83. if ( self::$_request != null)
  84. self::$_request = null;
  85. }
  86. protected function action($action) {
  87. $name = MST_String::camelize($action);
  88. $actName = $name . self::PF_ACTION;
  89. if (!method_exists($this, $actName))
  90. MST_Core::error(203, $actName);
  91. $actRef = new ReflectionMethod($this, $actName);
  92. if ($actRef- >isPrivate() || $actRef->isProtected()
  93. && !constant(MST_ActionController_Router::IS_MAP))
  94. MST_Core::error(203, $actName);
  95. if ($this->$actName() !== self::NO_RENDER && self::$_currentView == null)
  96. self::$_currentView = $action;
  97. return $this;
  98. }
  99. /**
  100. * Output, url jump
  101. */
  102. protected function redirect($ url) {
  103. if (defined(self::IS_RENDER)) return self::NO_RENDER;
  104. define(self::IS_RENDER, true);
  105. header('Location:'.linkUri($url));
  106. return $this ;
  107. }
  108. // render XML
  109. // render JAVASCRIPT
  110. protected function render(
  111. $mode = null,
  112. $content = null,
  113. array $options = null)
  114. {
  115. if (defined(self::IS_RENDER) ) return self::NO_RENDER;
  116. define(self::IS_RENDER, true);
  117. if ($mode == null) $mode = $this->defaultRender;
  118. if ($mode == self::VIEW)
  119. $content = $this->viewPath . '/' . $content;
  120. MST_ActionView::instance()
  121. ->assign($this)
  122. ->setOptions($options)
  123. ->render($mode , $content);
  124. return $this;
  125. }
  126. protected function customRender($file, $path, array $options = null) {
  127. return $this->render(self::CUSTOM_VIEW, array($file, $path), $options);
  128. }
  129. protected function setView($val) {
  130. self::$_currentView = $val;
  131. }
  132. protected function setViewOption($key, $val) {
  133. MST_ActionView::instance()->setOption($key, $val);
  134. return $this;
  135. }
  136. protected function getViewOption($key) {
  137. return MST_ActionView::instance()->getOption($key);
  138. }
  139. protected function setViewOptions(array $options) {
  140. MST_ActionView::instance()->setOptions($options);
  141. return $this;
  142. }
  143. protected function getViewOptions() {
  144. return MST_ActionView::instance()->getOptions();
  145. }
  146. protected function doComet(Closure $fn) {
  147. $times = 0;
  148. set_time_limit(0);
  149. while(true) {
  150. ob_flush();
  151. flush();
  152. $times++;
  153. $result = call_user_func($fn, $times, $this);
  154. if ($result === false) {
  155. break;
  156. }
  157. usleep(10000);
  158. sleep($this->comet);
  159. }
  160. }
  161. }
复制代码


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools