搜尋
首頁後端開發php教程理解PHP中的MVC编程之控制器_PHP

理解PHP中的MVC编程之控制器_PHP

Jun 01, 2016 pm 12:29 PM
classmodule控制器理解程式設計

MVC

简单来讲,控制器的作用就是接受请求。它使用获取的方法,在这里是通过URI,载入一个功能模块来刷新或者提交一个表述层。控制器将使用$_GET自动全局变量来判断载入哪一个模块。

  一个请求的例子,看起来像这样:

  http://example.com/index.php?module=login

  这看起来很简单,但是在实现的过程中却不是。这里是几个控制器能识别的argument部分:

  module定义了使用哪一个模块,如users模块
  class定义了使用哪一个功能类,如你想让用户login还是logout
  event定义了使用哪一个具体事件

  这样一个更复杂的例子可以解释上面的各个argument最终组成的请求URL:

  http://example.com/index.php?module=users&class=login

  这段请求告诉控制器应该载入users模块,然后是login类,最后因为没有定义具体事件,所以运行login::__default()默认事件。

  以下是具体代码部分:

<?php
 /**
  * index.php
  *
  * @author Joe Stump <joe@joestump.net>
  * @copyright Joe Stump <joe@joestump.net>
  * @license http://www.opensource.org/licenses/gpl-license.php
  * @package Framework
 */

 require_once('config.php');

 // {{{ __autoload($class)
 /**
  * __autoload
  *
  * Autoload is ran by PHP when it can't find a class it is trying to load.
  * By naming our classes intelligently we should be able to load most classes
  * dynamically.
  *
  * @author Joe Stump <joe@joestump.net>
  * @param string $class Class name we're trying to load
  * @return void
  * @package Framework
 */

 function __autoload($class)
 {
  $file = str_replace('_','/',substr($class,2)).'.php';
  require_once(FR_BASE_PATH.'/includes/'.$file);
 }
 // }}}

 if (isset($_GET['module'])) {
  $module = $_GET['module'];
  if (isset($_GET['event'])) {
   $event = $_GET['event'];
  } else {
   $event = '__default';
  }

 if (isset($_GET['class'])) {
  $class = $_GET['class'];
 } else {
  $class = $module;
 }

 $classFile = FR_BASE_PATH.'/modules/'.$module.'/'.$class.'.php';
 if (file_exists($classFile)) {
  require_once($classFile);
  if (class_exists($class)) {
   try {
    $instance = new $class();
    if (!FR_Module::isValid($instance)) {
     die("Requested module is not a valid framework module!");
    }

    $instance->moduleName = $module;
    if ($instance->authenticate()) {
     try {
      $result = $instance->$event();
      if (!PEAR::isError($result)) {
       $presenter = FR_Presenter::factory($instance->presenter,$instance);

      if (!PEAR::isError($presenter)) {
       $presenter->display();
      } else {
       die($presenter->getMessage());
      }
     }
    } catch (Exception $error) {
     die($error->getMessage());
    }
   } else {
    die("You do not have access to the requested page!");
   }
  } catch (Exception $error) {
   die($error->getMessage());
  }
 } else {
  die("An valid module for your request was not found");
 }
 } else {
  die("Could not find: $classFile");
 }
 } else {
  die("A valid module was not specified");
}

?>

  接下来是以上代码具体的注释:

  载入“config.php”

  定义__autoload()函数。这是PHP5里面的一个新函数,方便动态地载入各个类。

  如果一个argument被定义,那么载入相关的模块、类和具体事件

  接下来就是一些判断以及错误的具体操作

  最后一切无误后就载入表述层

  【友好URL】

  如果你觉得上面例子讲到的请求URL让你觉得不舒服的话,那么就用mod_rewrite来实现友好URL吧。接下来是作者给这个框架写的实际重写标准代码:

RewriteEngine On

# Change the URI here to whatever you want your homepage to be

RewriteRule ^/$ /index.php?module=welcome [L,QSA]

# Changes /index.php?module=welcome to /welcome

RewriteCond %{DOCUMENT_ROOT}/%{REQUEST_FILENAME} !-d

RewriteCond %{DOCUMENT_ROOT}/%{REQUEST_FILENAME} !-f

RewriteRule ^/([^/]*)$ /index.php?module=$1 [L,QSA]

# Changes /index.php?module=users&class=login to /users/login

RewriteCond %{DOCUMENT_ROOT}/%{REQUEST_FILENAME} !-d

RewriteCond %{DOCUMENT_ROOT}/%{REQUEST_FILENAME} !-f

RewriteRule ^/([^/]*)/([^/]*)$ /index.php?module=$1&class=$2 [L,QSA]

# Changes /index.php?module=users&class=login&event=foo

# to /users/login/foo.html

RewriteCond %{DOCUMENT_ROOT}/%{REQUEST_FILENAME} !-d

RewriteCond %{DOCUMENT_ROOT}/%{REQUEST_FILENAME} !-f

RewriteRule ^/([^/]*)/([^/]*)/([^/]*).html$ \

/index.php?module=$1&class=$2&event=$3 [L,QSA]

Extending the Controller

  【扩展控制器】

  拥有一个集中控制器的一点好处就是你加入一些功能后,马上就能通过控制器体现出来。以下是几个可以扩展一下这个控制器的点子,使这个框架的整体能力更加强大:
 
  你可以使用PHP5里一个新东西SoapServer来自动检测一个请求是否为SOAP

  你可以使用控制器来过滤所有的自动全局变量如$_GET和$_POST以防止恶意HTML代码等

  你可以使用控制器即时地转换表述层,比如从默认的方式转到PDF方式

  你可以直接在控制器中加入缓存机制,这样的好处是应用程序整体都能使用到缓存以提高效率

  当然,需要注意一点的是,你在控制器中所增加的功能将体现在程序全局。如你想过滤所有的自动全局变量,但是很多应用程序的管理员需要使用到一些HTML代码,反而成为一件棘手的事情(译者注:本人的想法是可以加一个if条件语句,在加载特定模块时不应用过滤功能即可)。
陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
如何使PHP應用程序更快如何使PHP應用程序更快May 12, 2025 am 12:12 AM

tomakephpapplicationsfaster,關注台詞:1)useopcodeCachingLikeLikeLikeLikeLikePachetoStorePreciledScompiledScriptbyTecode.2)MinimimiedAtabaseSqueriSegrieSqueriSegeriSybysequeryCachingandeffeftExting.3)Leveragephp7 leveragephp7 leveragephp7 leveragephpphp7功能forbettercodeefficy.4)

PHP性能優化清單:立即提高速度PHP性能優化清單:立即提高速度May 12, 2025 am 12:07 AM

到ImprovephPapplicationspeed,關注台詞:1)啟用opcodeCachingwithapCutoredUcescriptexecutiontime.2)實現databasequerycachingingusingpdotominiminimizedatabasehits.3)usehttp/2tomultiplexrequlexrequestsandreduceconnection.4 limitesclection.4.4

PHP依賴注入:提高代碼可檢驗性PHP依賴注入:提高代碼可檢驗性May 12, 2025 am 12:03 AM

依赖注入(DI)通过显式传递依赖关系,显著提升了PHP代码的可测试性。1)DI解耦类与具体实现,使测试和维护更灵活。2)三种类型中,构造函数注入明确表达依赖,保持状态一致。3)使用DI容器管理复杂依赖,提升代码质量和开发效率。

PHP性能優化:數據庫查詢優化PHP性能優化:數據庫查詢優化May 12, 2025 am 12:02 AM

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

簡單指南:帶有PHP腳本的電子郵件發送簡單指南:帶有PHP腳本的電子郵件發送May 12, 2025 am 12:02 AM

phpisusedforsenderemailsduetoitsbuilt-inmail()函數andsupportivelibrariesLikePhpMailerAndSwiftMailer.1)usethemail()functionForbasiceMails,butithasimails.2)butithasimail.2)

PHP性能:識別和修復瓶頸PHP性能:識別和修復瓶頸May 11, 2025 am 12:13 AM

PHP性能瓶颈可以通过以下步骤解决:1)使用Xdebug或Blackfire进行性能分析,找出问题所在;2)优化数据库查询并使用缓存,如APCu;3)使用array_filter等高效函数优化数组操作;4)配置OPcache进行字节码缓存;5)优化前端,如减少HTTP请求和优化图片;6)持续监控和优化性能。通过这些方法,可以显著提升PHP应用的性能。

PHP的依賴注入:快速摘要PHP的依賴注入:快速摘要May 11, 2025 am 12:09 AM

依賴性注射(DI)InphpisadesignPatternthatManages和ReducesClassDeptions,增強量強制性,可驗證性和MATIALWINABIOS.ItallowSpasspassingDepentenciesLikEdenciesLikedAbaseConnectionStoclasseconnectionStoclasseSasasasasareTers,interitationAseTestingEaseTestingEaseTestingEaseTestingEasingAndScalability。

提高PHP性能:緩存策略和技術提高PHP性能:緩存策略和技術May 11, 2025 am 12:08 AM

cachingimprovesphpermenceByStorcyResultSofComputationsorqucrouctationsorquctationsorquickretrieval,reducingServerLoadAndenHancingResponsetimes.feftectivestrategiesinclude:1)opcodecaching,whereStoresCompiledSinmememorytssinmemorytoskipcompliation; 2)datacaching datacachingsingMemccachingmcachingmcachings

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

WebStorm Mac版

WebStorm Mac版

好用的JavaScript開發工具

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具