[英]PHP views relate controllers
我想實現與MVC一樣連接到任何特定視圖的控制器。 我沒有使用PHP提供的任何框架。
因此,我需要一些指導和建議。
我有一些控制器和視圖。 對於我的觀點,我只想輸出我的數據。 現在,我要關心的是控制器中的函數(如create()
)如何獲取用戶在我的views/create.php
輸入數據的所有$_POST['params']
,並在create()
控制器的內部create()
新模型功能。
因此,現在,我正在考慮以這種方式進行操作,我將在控制器文件夾中創建MyViews類。 目的是加載特定的視圖,並將所有$_POST
參數放入一個對象中。 然后,每個類似Users_controllers的控制器都將創建MyViews 。 在Users_controllers函數中,例如create()
, destroy()
,我可能會在MyViews中使用該函數來加載特定的視圖以加載對象。
我找到了加載視圖的源
<?php
class MyView {
protected $template_dir = 'templates/';
protected $vars = array();
public function __construct($template_dir = null) {
if ($template_dir !== null) {
// Check here whether this directory really exists
$this->template_dir = $template_dir;
}
}
public function render($template_file) {
if (file_exists($this->template_dir.$template_file)) {
include $this->template_dir.$template_file;
} else {
throw new Exception('no template file ' . $template_file . ' present in directory ' . $this->template_dir);
}
}
public function __set($name, $value) {
$this->vars[$name] = $value;
}
public function __get($name) {
return $this->vars[$name];
}
} ?>
嗯,我不知道如何檢測_POST參數
if(isset($_POST['Post']))
{
$model->attributes=$_POST['Post'];
if($model->save())
$this->redirect(array('view','id'=>$model->id));
}
這是我觀察到的Yii框架。 加載特定視圖后,如何檢測參數是$_POST
還是$_GET
。
有任何指導和建議來存檔我的任務嗎?
不用提問
您有一個主要問題:表達意圖的能力非常有限。 您提出的問題實際上與您的問題無關。
根據我的收集,您需要檢測用戶發出的POST
或GET
請求。 要直接檢測它,可以檢查$_SERVER['REQUEST_METHOD']
,但是使用控制器檢查它可能會很麻煩。 您將最終得到許多控制器的方法,這些方法的行為根據請求方法而有所不同。
由於您沒有使用任何流行的框架,因此建議您將這個決定委托給路由機制。
在我看來,一種很好的處理方法是在控制器的方法名稱前添加請求方法: postLogin()
, getArticles()
等。您可以在此處找到一些其他示例。 如果有POST
請求時,它會在什么$_POST
陣列。
所謂的“視圖”實際上是模板。 如果閱讀本文 ,您會注意到,該代碼實際上是
MyView
的改進版本。 視圖不是模板。 視圖是包含表示邏輯並操縱多個模板的實例。
PS:如果您正在探索與PHP有關的MVC和MVC啟發式模式,那么您可能會發現這篇文章很有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.