search

简单来讲,控制器的作用就是接受请求。它使用获取的方法,在这里是通过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被定义,那么载入相关的模块、类和具体事件

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

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


Pretty URLs 【友好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条件语句,在加载特定模块时不应用过滤功能即可)。

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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

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 Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment