Table of Contents
用 Composer构建自己的 PHP 框架之设计 MVC,composermvc
控制器成功!
'.$row["title"].'
我是内容呀~~
用php语言搭建mvc框架
php mvc框架
Home php教程 php手册 用 Composer构建自己的 PHP 框架之设计 MVC,composermvc

用 Composer构建自己的 PHP 框架之设计 MVC,composermvc

Jun 13, 2016 am 09:22 AM
composer mvc mvc framework php frame

用 Composer构建自己的 PHP 框架之设计 MVC,composermvc

回顾

在上一篇教程中,我们使用 codingbean/macaw 这个 Composer 包构建了两条简单路由,第一条是响应 GET ‘/fuck' 的,另一条会 hold 住所有请求。其实对 PHP 框架来说,有了路由就有了一切。所以接下来我们要做的事情就是让 MFFC 框架更加规范,更加丰满。

这就牵扯到了 PHP 框架另外的价值:确立开发规范以便于`多人协作`,使用 ORM`、`模板引擎 等工具以`提高开发效率`。

正式开始规划文件夹

新建 MFFC/app 文件夹,在 app 中创建 controllers、models、views 三个文件夹,开始正式开始踏上 MVC 的征程。

(谁说我抄 Laravel 了,我抄的明明是 Rails :-D)

使用命名空间

新建 controllers/BaseController.php 文件:

/**<br>* BaseController<br>*/<br>class BaseController<br>{<br>  <br>  public function __construct()<br>  {<br>  }<br>}<br>
Copy after login

新建 controllers/HomeController.php 文件:


<pre data-lang="php">
/**<br>* \HomeController<br>*/<br>class HomeController extends BaseController<br>{<br>  <br>  public function home()<br>  {<br>    echo "<h1 id="控制器成功">控制器成功!</h1>";<br>  }<br>}
Copy after login

增加一条路由: Macaw::get('', 'HomeController@home');`,打开浏览器直接访问 http://127.0.0.1:81/`,出现以下提示:

Fatal error: Class 'HomeController' not found in /Library/WebServer/Documents/wwwroot/MFFC/vendor/codingbean/macaw/Macaw.php on line 93
Copy after login

为什么没找到 HomeController 类?因为我们没有让他自动加载,修改 composer.json 为:

{<br>  "require": {<br>    "codingbean/macaw": "dev-master"<br>  },<br>  "autoload": {<br>    "classmap": [<br>      "app/controllers",<br>      "app/models"<br>    ]<br>  }<br>}
Copy after login

运行 composer dump-autoload`,稍等片刻,刷新,你将看到以下内容(别忘了调节编码哦~):


恭喜你,命名空间使用成功!

连接数据库

新建 models/Article.php 文件,内容为(数据库密码请自行更改):

/**<br>* Article Model<br>*/<br>class Article<br>{<br>  public static function first()<br>  {<br>    $connection = mysql_connect("localhost","root","password");<br>    if (!$connection) {<br>      die('Could not connect: ' . mysql_error());<br>    }
Copy after login
    mysql_set_charset("UTF8", $connection);
Copy after login
    mysql_select_db("mffc", $connection);
Copy after login
    $result = mysql_query("SELECT * FROM articles limit 0,1");
Copy after login
    if ($row = mysql_fetch_array($result)) {<br>      echo '<h1 id="row-title">'.$row["title"].'</h1>';<br>      echo '<p>'.$row["content"].'</p>';<br>    }
Copy after login
    mysql_close($connection);<br>  }<br>}
Copy after login

修改 controllers/HomeController.php 文件:


<p>刷新,这时候会得到 Article 类未找到的信息,因为我们没有更新自动加载配置:</p>
<pre data-lang="html">
composer dump-autoload
Copy after login

在等待的时间里,我们去建立数据库 mffc`,在里面建立表 articles`,设计两个字段 title`、`content 用于记录信息,并填充进至少一条数据。你也可以在建立完成 mffc 数据库以后运行以下 SQL 语句:

DROP TABLE IF EXISTS `articles`;<br>CREATE TABLE `articles` (<br>  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,<br>  `title` varchar(255) DEFAULT NULL,<br>  `content` longtext,<br>  PRIMARY KEY (`id`)<br>) ENGINE=InnoDB DEFAULT CHARSET=utf8;<br>LOCK TABLES `articles` WRITE;<br>/*!40000 ALTER TABLE `articles` DISABLE KEYS */;<br>INSERT INTO `articles` (`id`, `title`, `content`)<br>VALUES<br> (1,'我是标题','<h3 id="我是内容呀">我是内容呀~~</h3><p>我真的是内容,不信算了,哼~ O(∩_∩)O</p>'),<br> (2,'我是标题','<h3 id="我是内容呀">我是内容呀~~</h3><p>我真的是内容,不信算了,哼~ O(∩_∩)O</p>');<br>/*!40000 ALTER TABLE `articles` ENABLE KEYS */;<br>UNLOCK TABLES;
Copy after login

然后,刷新!你将看到以下页面:


恭喜你!MVC 中的 M 和 C 都已经实现!接下来我们开始调用 V (视图)。

调用视图

修改 models/Article.php 为:

/**<br>* Article Model<br>*/<br>class Article<br>{<br>  public static function first()<br>  {<br>    $connection = mysql_connect("localhost","root","C4F075C4");<br>    if (!$connection) {<br>      die('Could not connect: ' . mysql_error());<br>    }<br>    mysql_set_charset("UTF8", $connection);<br>    mysql_select_db("mffc", $connection);<br>    $result = mysql_query("SELECT * FROM articles limit 0,1");<br>    if ($row = mysql_fetch_array($result)) {<br>      return $row;<br>    }<br>    mysql_close($connection);<br>  }<br>}
Copy after login

将包含查询结果的数组返回。修改 HomeController:

/**<br>* \HomeController<br>*/<br>class HomeController extends BaseController<br>{<br>  public function home()<br>  {<br>    $article = Article::first();<br>    require dirname(__FILE__).'/../views/home.php';<br>  }<br>}
Copy after login

保存,刷新,你将得到跟上面一模一样的页面,视图调用成功!

几乎所有人都是通过学习某个框架来了解 MVC 的,这样可能框架用的很熟,一旦离了框架一个简单的页面都写不了,更不要说自己设计 MVC 架构了,其实这里面也没有那么多门道,原理非常清晰,我说说我的感悟:

1. PHP 框架再牛逼,他也是 PHP,也要遵循 PHP 的运行原理和基本哲学。抓住这一点我们就能很容易地理解很多事情。

2. PHP 做的网站从逻辑上说,跟 php test.php 没有任何区别,都只是一段字符串作为参数传递给 PHP 解释器而已。无非就是复杂的网站会根据 URL 来调用需要运行的文件和代码,然后返回相应的结果。

3. 无论我们看到的是 CodeIgniter 这样 180 个文件`组成的“小框架”,还是 Laravel 这样`加上 vendor 一共 3700 多个文件`的 “大框架”,他们都会在每一个 URL 的驱动下,组装一段可以运行的字符串,传给 PHP 解释器,再把从 PHP 解释器返回的字符串传给访客的浏览器。

4. MVC 是一种逻辑架构,本质上是为了让人脑这样的超低 RAM 的计算机能够制造出远超人脑 RAM 的大型软件,其实 MVC 架构在 GUI 软件出现以前就已经成形,命令行输出也是视图嘛。

5. 在 MFFC 里,一个 URL 驱动框架做的事情基本是这样的:入口文件 require 控制器,控制器 require 模型,模型和数据库交互得到数据返回给控制器,控制器再 require 视图,把数据填充进视图,返回给访客,流程结束。

用php语言搭建mvc框架

你要不是太追求自己的控制,建议用现成的mvc框架,大为缩小开发时间
 

php mvc框架

MVC不是建立几个包而已,而是一种思想,当然几个包会让你把这个思想实例出来- -,比如说你有一个表,而已你实例这个表的话,就要有一个类来囊括其中的字段,包括一些_get,_set方法,然后用另一个类继承此类,封装一些添删改查的等等方法,这个类就可以理解成Model层,可以放在一个包下,而逻辑页面望望要require_noce此文件类来实例化此类,通过对象来调用其中的方法,进而显示给客户,php中C层和V层在不用模板的情况下(比如说smarty)不用分离的那么明显,要么怎么是php那~小快灵么~整体上不局限于java那种纯的面向对象,但又不失对数据安全性与维护性特点,这就是php的MVC~
 

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)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months 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)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles