PHP实现MVC开发: 一个简单的MVC
今天研究了下PHP MVC结构,所以决定自己写个简单的MVC,以待以后有空再丰富。
至于什么MVC结构,其实就是三个Model,Contraller,View单词的简称,,Model,主要任务就是把数据库或者其他文件系统的数据按
照我们需要的方式读取出来。View,主要负责页面的,把数据以html的形式显示给用户。Controller,主要负责业务逻辑,根据用户的
Request进行请求的分配,比如说显示登陆界面,就需要调用一个控制器userController的方法loginAction来显示。
下面我们用PHP来创建一个简单的MVC结构系统。
首先创建单点入口,即bootstrap文件index.php,作为整个MVC系统的唯一入口。什么是单点入口呢?所谓单点入口就是整个应用程序只有一
个入口,所有的实现都通过这个入口来转发。为什么要做到单点入口呢?单点入口有几大好处:第一、一些系统全局处理的变量,类,方法都可以在这里进行处理。
比如说你要对数据进行初步的过滤,你要模拟session处理,你要定义一些全局变量,甚至你要注册一些对象或者变量到注册器里面。第二、程序的架构更加
清晰明了。当然好处还有很多的。:)
<?php <br>include("core/ini.php");<br>initializer::initialize();<br>$router = loader::load("router");<br>dispatcher::dispatch($router);<br>
这个文件就只有4句,我们现在一句句来分析。
include(”core/ini.php”);
我们来看core/ini.php
<?php <br>set_include_path(get_include_path() . PATH_SEPARATOR . "core/main");<br>//set_include_path — Sets the include_path configuration option<br>function __autoload($object){<br> require_once("{$object}.php");<br>}<br>
这个文件首先设置了include_path,也就是我们如果要找包含的文件,告诉系统在这个目录下查找。其实我们定义__autoload()方法,这个方法是在PHP5增加的,就是当我们实例化一个函数的时候,如果本文件没有,就会自动去加载文件。官方的解释是:
Many developers writing object-oriented applications create one PHP
source file per-class definition. One of the biggest annoyances is
having to write a long list of needed includes at the beginning of each
script (one for each class).
In PHP 5, this is no longer necessary. You may define an __autoload function which is automatically called in case you are trying to use a class/interface which hasn’t been defined yet. By calling this function the scripting engine is given a last chance to load the class before PHP fails with an error.
接下来我们看下面一句
initializer::initialize();
这就话就是调用initializer类的一个静态函数initialize,因为我们在ini.php,设置了include_path,以及定义了__autoload,所以程序会自动在core/main目录查找initializer.php.
initializer.php文件如下:
<?php <br>class initializer<br>{<br> public static function initialize() {<br> set_include_path(get_include_path().PATH_SEPARATOR . "core/main");<br> set_include_path(get_include_path().PATH_SEPARATOR . "core/main/cache");<br> set_include_path(get_include_path().PATH_SEPARATOR . "core/helpers");<br> set_include_path(get_include_path().PATH_SEPARATOR . "core/libraries");<br> set_include_path(get_include_path().PATH_SEPARATOR . "app/controllers");<br> set_include_path(get_include_path().PATH_SEPARATOR."app/models");<br> set_include_path(get_include_path().PATH_SEPARATOR."app/views");<br> //include_once("core/config/config.php");<br> }<br>}<br>?><br>
这个函数很简单,就只定义了一个静态函数,initialize函数,这个函数就是设置include_path,这样,以后如果包含文件,或者__autoload,就会去这些目录下查找。
OK,我们继续,看第三句
$router = loader::load(”router”);
这句话也很简单,就是加载loader函数的静态函数load,下面我们来loader.php
<?php <br>class loader<br>{<br> private static $loaded = array();<br> public static function load($object){<br> $valid = array( "library",<br> "view",<br> "model",<br> "helper",<br> "router",<br> "config",<br> "hook",<br> "cache",<br> "db");<br> if (!in_array($object,$valid)){<br> throw new Exception("Not a valid object '{$object}' to load");<br> }<br> if (empty(self::$loaded[$object])){<br> self::$loaded[$object]= new $object();<br> }<br> return self::$loaded[$object];<br> }<br>}<br>
这个文件就是去加载对象,因为以后我们可能会丰富这个MVC系统,会有model,helper,config等等的组件。如果加载的组件不在有效 的范围内,我们抛出一个异常。如果在的话,我们实例化一个对象,其实这里用了单件设计模式。也就是这个对象其实就只能是一个实例化对象,如果没有实例化, 创建一个,如果存在的,则不实例化。
好,因为我们现在要加载的是router组件,所以我们看下router.php文件,这个文件的作用就是映射URL,对URL进行解析。
router.php
<?php <br>class router<br>{<br> private $route;<br> private $controller;<br> private $action;<br> private $params;<br> public function __construct()<br> {<br> $path = array_keys($_GET);<br> if (!isset($path[0])){<br> if (!empty($default_controller))<br> $path[0] = $default_controller;<br> else<br> $path[0] = "index";<br> }<br> $route= $path[0];<br> $this->route = $route;<br> $routeParts = split( "/",$route);<br> $this->controller=$routeParts[0];<br> $this->action=isset($routeParts[1])? $routeParts[1]:"base";<br> array_shift($routeParts);<br> array_shift($routeParts);<br> $this->params=$routeParts;<br> }<br> public function getAction() {<br> if (empty($this->action)) $this->action="main";<br> return $this->action;<br> }<br> public function getController() {<br> return $this->controller;<br> }<br> public function getParams() {<br> return $this->params;<br> }<br>}<br>
我们可以看到,首先我们是拿到$_GET,用户Request的URL,然后从URL里我们解析出Controller和Action,以及Params
比如我们的地址是http://www.tinoweb.cn/user/profile/id/3
那么从上面的地址,我们可以拿到controller是user,action似乎profile,参数是id以及3
OK我们看最后一句,就是
dispatcher::dispatch($router);
这句话的意思很明了,就是拿到URL解析的结果,然后通过dispatcher来分发controlloer及action来Response给用户
好,我们来看下dispatcher.php文件
<br>class dispatcher<br>{<br> public static function dispatch($router)<br> {<br> global $app;<br> ob_start();<br> $start = microtime(true);<br> $controller = $router->getController();<br> $action = $router->getAction();<br> $params = $router->getParams();<br> $controllerfile = "app/controllers/{$controller}.php";<br> if (file_exists($controllerfile)){<br> require_once($controllerfile);<br> $app = new $controller();<br> $app->setParams($params);<br> $app->$action();<br> if (isset($start)) echo "<br><br>Tota1l time for dispatching is : ".(microtime(true)-$start)." seconds.<br><br>";<br> $output = ob_get_clean();<br> echo $output;<br> }else{<br> throw new Exception("Controller not found");<br> }<br> }<br>}<br>
这个类很明显,就是拿到$router来,寻找文件中的controller和action来回应用户的请求。
OK,我们一个简单的,MVC结构,就这样,当然这里还不能算是一个很完整的MVC,因为这里还没有涉及到View和Model,有空我再这里丰富。
我们来写个Controller文件来测试下上面的这个系统。
我们在app/controllers/下创建一个user.php文件
//user.php<br><?php <br>class user<br>{<br> function base()<br> {<br> }<br> public function login()<br> {<br> echo 'login html page';<br> }<br> public function register()<br> {<br> echo 'register html page';<br> }<br> public function setParams($params){<br> var_dump($params);<br> }<br>}<br>
然后你可以在浏览器中输入http://localhost/index.php?user/register 或者 http://localhost/index.php?user/login来测试下。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

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 uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

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 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.

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.
