1. 程式人生 > >PHP搭建自己的MVC框架8 檢視層

PHP搭建自己的MVC框架8 檢視層

接下來實現檢視層

檢視層包括變數賦值(assign) 和 呼叫模板(display)

控制器繼承基類

<?php
namespace app\ctrl;
class indexCtrl extends \core\mymvc
{
    public function index(){$data='hello world';
$title='試圖檔案';
$this->assign("data",$data);
$this->assign("title",$title);
$this->display("index.html");
}
}
然後在基類mymvc中去增加方法
public function 
assign($name,$value) { $this->assign[$name] = $value; } public function display($file) { $file = APP.'/views/'.$file; if(is_file($file)){ extract($this->assign); include $file; } }
注意使用extract函式 該函式的作用是

該函式使用陣列鍵名作為變數名,使用陣列鍵值作為變數值。針對陣列中的每個元素,將在當前符號表中建立對應的一個變數。

第二個引數 type 用於指定當某個變數已經存在,而陣列中又有同名元素時,extract() 函式如何對待這樣的衝突。

該函式返回成功匯入到符號表中的變數數目。

具體檢視 http://www.w3school.com.cn/php/func_array_extract.asp

在app目錄下新建views目錄 新建一個index.html頁面