Home Backend Development PHP Tutorial MVCwithPHP(二)_PHP

MVCwithPHP(二)_PHP

Jun 01, 2016 pm 12:40 PM
function public function this

MVC

MVC with PHP(一)中的bug的问题是存在,最大的问题是日志系统的问题,等完成这这个介绍后我后把全部更正的程序源码打包
出来,这里就暂时不做更改了.
先来看看在application.class.php中是如何建立controller实例的:

PHP代码:--------------------------------------------------------------------------------
/**
* 执行函数
*
* 此类唯一对外的一个接口
**/
public function run()
{
$this->parsePath();
$this->checkSecurity($this->module, $this->action);
1. $controller = new $this->controllerClassName();
2. $controller->{$this->action}();
$this->writeLog($this->module, $this->action);
}

--------------------------------------------------------------------------------

Application这个类在实例后唯一可进行调用的一个函数,它根据用户的URL请求来分析得出所需要的Controller类名,然后实例化这个类(上面标1的地方),再调用从URL中获取的动作名称(上面标2的地方),

这个举一个简单的例子:
URL: http://localhost/?module=news&action=showList
Application通过分析这个URL重到controllerClassName=news, action=showList,然后它将在包含处理这个controller类的文件名(在Application->getControllerFile()中进行),然后实例化News这个
controller类(标1的地方), 随后调用它的动作showList(标2的地方).
来看看newsController.php中的内容:
=============================================================

PHP代码:--------------------------------------------------------------------------------

/**
* FileName: newsController.php
* Introduce: 新闻控制类
*
* @author: 大师兄
* @Email: teacherli@163.com
* @version $Id$
* @copyright 2004-10-26
**/
include_once ("./controller/comm/controller.class.php");
include_once ("./model/news/newsModel.php");

class NewsController extends Controller
{
private $model;

/**
* 构造函数
*
**/
public function __construct()
{
parent::__construct();
$this->model = new NewsModel();
$this->setSmartyTemplate_dir("./view/news");
}

/**
* 显示新闻列表
*
**/
public function showList()
{
1. $newsList = & $this->model->getList();

2. $this->smarty->assign("newsList", $newsList);
3. unset($newsList);

4. $this->smarty->display("newsList.html");
}
}
?>

--------------------------------------------------------------------------------

==============================================================
首先,NewsController类继承自公共类Controller,在类进行初始化时产生一个NewsModel类,这个类是一个model类,由这个类负责新闻模块所有的对数据库的交互. parent::__construct()调用父类的构造函数,完成对view的控制类Smarty的初始化.$this->setSmartyTemplate_dir("./view/news")将模板目录定位在./view/news目录.

然后看我们上面的例子,请求URL为http://localhost/?module=news&actio...List,表示要调用
showList这个动作,看NewsController类的showList()成员函数:
1. $newsList = & $this->model->getList(): $this->model在NewsController初始化时建立,这一句要使用$this->model从数据库里提取出一个新闻列表,这个列表当然就是Smarty在操作循环块时需要的二维数组了,在NewsModel类中,它是采用ADODB回传的一个二维数组.
2. $this->smarty->assign("newsList", $newsList): 熟悉吧,smarty中循环块的程序控制
3. unset($newsList):考虑到效率问题,对于这些临时变量在使用完成后即时将它unset。
4. $this->smarty->display("newsList.html"):使用smarty来显示view.

大家看明白了吗?实际上controller类要做的事情就是这样:1.调用model从数据库取出记录 2.操

作Smarty显示view。
再来看看NewsController的父类Controller类的源码:
===========================================================

PHP代码:--------------------------------------------------------------------------------

/**
* FileName: controller.class.php
* Introduce: Base class of controller
*
* @author: 李晓军
* @Email: teacherli@163.com
* @version $Id$
* @copyright 2004-10-26
**/

include_once ("./comm/smarty/Smarty.class.php");
include_once ("./comm/config.inc.php");

abstract class Controller
{
private $smarty;

/**
* 系统构建函数
* 初始化Smarty
**/
function __construct()
{
$this ->smarty = new Smarty();

$this->smarty->template_dir = "./view/templates";
$this->smarty->compile_dir = "./view/templates_c";
$this->smarty->cache_dir = "./view/cache";
$this->smarty->cache_lifetime = 60 * 60 * 24;
$this->smarty->caching = false;
$this->smarty->left_delimiter = " $this->smarty->right_delimiter = "}>";
}

/**
* 设置smarty模板路径
*
* @param string $template
**/
public function setSmartyTemplate_dir($template)
{
$this->smarty->template_dir = $template;
}

/**
* 设置smarty是否进行缓存
*
* @param boolean $cache
**/
public function setSmartyCache($cache = false)
{
$this->smarty->cache = $cache;
}

/**
* 设置smarty缓存时间
*
* @param string $cacheLifetime
**/
public function setSmartyCacheTime($cacheLifetime)
{
$this->smarty->cache_lifetime = $cacheLifetime;
}

/**
* 动作被执行后一个短暂的提示
*
* @param string $module 重新定向到的模块名称
* @param string $action 重新定向的动作名称
* @param string $params 参数名称
* @param string $message 提示信息
**/
public function redirect($module, $action, $params="", $message="动作已经被成功执

行")
{
$time = WAIT_FOR_TIME;
$params = ("" == $params) ? "" : "&$params";
$URL = "?module=" . $module . "&action=" . $action . $params;

//重新定Smarty模板目录至公用目录
$this->setSmartyTemplate_dir("./view/templates");
$this->smarty->assign("URL", $URL); //重定向的目录
$this->smarty->assign("message", $message); //提示信息
$this->smarty->assign("time", $time);
$this->smarty->display("wait.html");
}

/**
* 调用本类不存在的方法时进行的处理
*
* @param string $name
* @param string $parameter
**/
public function __call($name, $parameter)
{
throw new ActionNotAllowException("对不起,你所请求的动作 $name 没有定义

...
");
}

/**
* 析构函数
*
**/
public function __destruct()
{
unset($this->smarty);
}
}
?>

--------------------------------------------------------------------------------

==============================================
Controller是一个抽象类,也就是说它不可以直接使用new 来产生一个实例对象,在类的构造函数里产生一个Smarty类,并对其进行基本的设置。其它的几个函数是对Smarty对象进行设置的成员函数, 这里来看看这两个函数:

public function redirect($module, $action, $params="", $message="动作已经被成功执行"):
这是一个重新定向成员函数,它的作用是当我们对模块进行一些操作后给出的提示页面,然后经过设置好的时间自动重新定向到另一个位置,例如我们要对新闻进行一些删除,删除成功后我们要给用户返回这样一个页面,告诉用户操作已经成功,请待n秒后自动返回....这在论坛中是很常见的,这里我也引用了这样的策略。

public function __call($name, $parameter):
当类调用类没有声明的函数时使用这个函数进行处理,这可是个好东东,有了它,可以使用对程序

的控制更加简单了,大家可以试试这个方法....

好了,Controller 部分就谈到这里了。

Statement of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Tips for dynamically creating new functions in golang functions Tips for dynamically creating new functions in golang functions Apr 25, 2024 pm 02:39 PM

Go language provides two dynamic function creation technologies: closure and reflection. closures allow access to variables within the closure scope, and reflection can create new functions using the FuncOf function. These technologies are useful in customizing HTTP routers, implementing highly customizable systems, and building pluggable components.

Considerations for parameter order in C++ function naming Considerations for parameter order in C++ function naming Apr 24, 2024 pm 04:21 PM

In C++ function naming, it is crucial to consider parameter order to improve readability, reduce errors, and facilitate refactoring. Common parameter order conventions include: action-object, object-action, semantic meaning, and standard library compliance. The optimal order depends on the purpose of the function, parameter types, potential confusion, and language conventions.

How to write efficient and maintainable functions in Java? How to write efficient and maintainable functions in Java? Apr 24, 2024 am 11:33 AM

The key to writing efficient and maintainable Java functions is: keep it simple. Use meaningful naming. Handle special situations. Use appropriate visibility.

Complete collection of excel function formulas Complete collection of excel function formulas May 07, 2024 pm 12:04 PM

1. The SUM function is used to sum the numbers in a column or a group of cells, for example: =SUM(A1:J10). 2. The AVERAGE function is used to calculate the average of the numbers in a column or a group of cells, for example: =AVERAGE(A1:A10). 3. COUNT function, used to count the number of numbers or text in a column or a group of cells, for example: =COUNT(A1:A10) 4. IF function, used to make logical judgments based on specified conditions and return the corresponding result.

Comparison of the advantages and disadvantages of C++ function default parameters and variable parameters Comparison of the advantages and disadvantages of C++ function default parameters and variable parameters Apr 21, 2024 am 10:21 AM

The advantages of default parameters in C++ functions include simplifying calls, enhancing readability, and avoiding errors. The disadvantages are limited flexibility and naming restrictions. Advantages of variadic parameters include unlimited flexibility and dynamic binding. Disadvantages include greater complexity, implicit type conversions, and difficulty in debugging.

What are the benefits of C++ functions returning reference types? What are the benefits of C++ functions returning reference types? Apr 20, 2024 pm 09:12 PM

The benefits of functions returning reference types in C++ include: Performance improvements: Passing by reference avoids object copying, thus saving memory and time. Direct modification: The caller can directly modify the returned reference object without reassigning it. Code simplicity: Passing by reference simplifies the code and requires no additional assignment operations.

What is the difference between custom PHP functions and predefined functions? What is the difference between custom PHP functions and predefined functions? Apr 22, 2024 pm 02:21 PM

The difference between custom PHP functions and predefined functions is: Scope: Custom functions are limited to the scope of their definition, while predefined functions are accessible throughout the script. How to define: Custom functions are defined using the function keyword, while predefined functions are defined by the PHP kernel. Parameter passing: Custom functions receive parameters, while predefined functions may not require parameters. Extensibility: Custom functions can be created as needed, while predefined functions are built-in and cannot be modified.

C++ Function Exception Advanced: Customized Error Handling C++ Function Exception Advanced: Customized Error Handling May 01, 2024 pm 06:39 PM

Exception handling in C++ can be enhanced through custom exception classes that provide specific error messages, contextual information, and perform custom actions based on the error type. Define an exception class inherited from std::exception to provide specific error information. Use the throw keyword to throw a custom exception. Use dynamic_cast in a try-catch block to convert the caught exception to a custom exception type. In the actual case, the open_file function throws a FileNotFoundException exception. Catching and handling the exception can provide a more specific error message.

See all articles