欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

php打造屬于自己的MVC框架

 更新時間:2012年03月07日 23:13:34   作者:  
本篇先介紹一下php的MVC實(shí)現(xiàn)原理,我們框架的MVC部分也是基于此原理實(shí)現(xiàn)的,但是今天的代碼并不是框架內(nèi)的代碼,僅僅為說明原理
一、文件結(jié)構(gòu)
建立3個文件夾
controller文件夾存放控制器文件
view文件夾存放視圖文件
model文件夾存放數(shù)據(jù)文件
建立1個index.php 作為唯一入口
二、控制器
我們在controller文件夾下建立一個democontroller.php文件,文件內(nèi)容如下
復(fù)制代碼 代碼如下:

<?php
class DemoController
{
function index()
{
echo('hello world');
}
}
/* End of file democontroller.php */

這個文件里面我們只是建立了一個名為DemoController的對象并包含一個index的方法,該方法輸出hello world。下面在index.php中執(zhí)行DemoController中index方法。
index.php的代碼如下
復(fù)制代碼 代碼如下:

<?php
require('controller/democontroller.php');
$controller=new DemoController();
$controller->index();
/* End of file index.php */

運(yùn)行index.php,ok如愿我們看到了我們久違的hello world。這兩個文件非常簡單,但也揭示了一點(diǎn)點(diǎn)mvc的本質(zhì),通過唯一入口運(yùn)行我們要運(yùn)行的控制器。當(dāng)然controller部分應(yīng)該是由uri來決定的,那么我們來改寫一下index.php使他能通過uri來決定運(yùn)行那個controller。
index.php改寫代碼如下:
復(fù)制代碼 代碼如下:

<?php
$c_str=$_GET['c'];
//獲取要運(yùn)行的controller
$c_name=$c_str.'Controller';
//按照約定url中獲取的controller名字不包含Controller,此處補(bǔ)齊。
$c_path='controller/'.$c_name.'.php';
//按照約定controller文件要建立在controller文件夾下,類名要與文件名相同,且文件名要全部小寫。
$method=$_GET['a'];
//獲取要運(yùn)行的action
require($c_path);
//加載controller文件
$controller=new $c_name;
//實(shí)例化controller文件
$controller->$method();
//運(yùn)行該實(shí)例下的action
/* End of file index.php */

在瀏覽器中輸入http://localhost/index.php?c=demo&a=index,得到了我們的hello world。當(dāng)然如果我們有其他的controller并且要運(yùn)行它,只要修改url參數(shù)中的c和a的值就可以了。
這里有幾個問題要說明一下。
一、php是動態(tài)語言,我們直接可以通過字符串new出我們想要的對象和運(yùn)行我們想要的方法,即上面的new $c_name,我們可以理解成new 'DemoController',因?yàn)?c_name本身的值就是'DemoController',當(dāng)然直接new 'DemoController'這么寫是不行的,其中的'DemoController'字符串必須通過一個變量來中轉(zhuǎn)一下。方法也是一樣的。
二、我們在url中c的值是demo,也就是說$c_name 的值應(yīng)該是demoController呀,php不是區(qū)分大小寫嗎,這樣也能運(yùn)行嗎?php區(qū)分大小寫這句話不完整,在php中只有變量(前面帶$的)和常量(define定義的)是區(qū)分大小寫的,而類名方,法名甚至一些關(guān)鍵字都是不區(qū)分大小寫的。而true,false,null等只能全部大寫或全部小寫。當(dāng)然我們最好在實(shí)際編碼過程中區(qū)分大小寫。
三、視圖
我們在前面的controller中只是輸出了一個“hello world”,并沒有達(dá)到mvc的效果,下面我將在此基礎(chǔ)上增加視圖功能,相信到這里大家基本已經(jīng)能想到如何添加視圖功能了。對,就是通過萬惡的require或者include來實(shí)現(xiàn)。
首先我們在view文件夾下建立一個index.php,隨便寫點(diǎn)什么(呵呵,我寫的還是hello world)。之后我們改寫一下我們之前的DemoController。代碼如下:
復(fù)制代碼 代碼如下:

<?php
class DemoController
{
function index()
{
require('view/index.php');
}
}
/* End of file democontroller.php */

再在瀏覽器中運(yùn)行一下,看看是不是已經(jīng)輸出了我們想要的內(nèi)容了。
接著我們通過controller向view傳遞一些數(shù)據(jù)看看,代碼如下:
復(fù)制代碼 代碼如下:

<?php
class DemoController
{
function index()
{
$data['title']='First Title';
$data['list']=array('A','B','C','D');
require('view/index.php');
}
}
/* End of file democontroller.php */

view文件夾下index.php文件代碼如下:
復(fù)制代碼 代碼如下:

<html>
<head>
<title>demo</title>
</head>
<body>
<h1><?php echo $data['title'];?></h1>
<?php
foreach ($data['list'] as $item)
{
echo $item.'<br>';
}
?>
</body>
</html>

相關(guān)文章

最新評論