【发布时间】:2011-10-15 13:18:56
【问题描述】:
在控制器或模型中存储变量的最佳做法是什么? 例如在执行脚本时。它从会话中获取用户 ID 并获取它是什么类型的用户,超级管理员、管理员、服务代表、销售代表。我们还检查用户 ID 属于哪个帐户,并获取该帐户的所有设置。
我的问题是我在哪里存储这些值,在控制器或模型中?
提前谢谢你。
【问题讨论】:
标签: php model-view-controller model controller
在控制器或模型中存储变量的最佳做法是什么? 例如在执行脚本时。它从会话中获取用户 ID 并获取它是什么类型的用户,超级管理员、管理员、服务代表、销售代表。我们还检查用户 ID 属于哪个帐户,并获取该帐户的所有设置。
我的问题是我在哪里存储这些值,在控制器或模型中?
提前谢谢你。
【问题讨论】:
标签: php model-view-controller model controller
在 PHP 中,考虑真正的 MVC 模型有点奇怪,因为您的模型、视图和控制器可以访问 $_SESSION。
例如,如果您要让用户登录,您的模型将执行以下操作:
class Model{
...
static function login($username, $password){
$result = Model::getUser($username, $password);
if(empty($result)){
return false;
}
else
{
$_SESSION['userid'] = $result['id'];
// Assign other information you think you'll need in the session here
}
}
static function loggedIn(){
if(isset($_SESSION['userid']){
return true;
}
else
{
return false;
}
}
static function getAttribute($attr){
return $_SESSION[$attr];
}
...
}
class Controller{
function someFxn(){
$userInfo = Model::getAttribute('someAttr');
}
}
很明显,这段代码需要扩展,但它应该正确地显示概念。我还在模型中使用了静态函数,但您可以将模型设为对象。
我的问题是我应该在哪里存储这些设置,在模型中,还是将其传递回控制器,控制器将存储这些设置?
根据您的操作方式,您可以每次通过模型从数据库中获取设置,也可以将它们存储在会话中。在 $_SESSION 中存储东西可以减少数据库调用。在实践中,模型操作 $_SESSION 或数据库。如果您的模型特定于某些东西(您可以创建自己的用户模型),那么您实例化该对象并将您的信息存储在私有成员中。
控制器的目的是从模型中获取信息,然后相应地呈现您的页面。真正的 MVC 数据流是这样工作的:
【讨论】:
您将它们存储在模型中(从数据库中获取它们),使用控制器拉取它们(在页面加载时),然后在视图中显示它们的结果(通过在需要时调用控制器类)。
这就是MVC的基本原理……
祝你好运!
我会给你一个可以出售的汽车对象的简单例子......这个例子很烂,但你可以从中了解 MVC 是如何工作的......
<?
// Data
class Car
{
private $_color;
public function setColor($newC)
{
$this->_color = $newC;
}
public function getColor()
{
return $this->_color;
}
private $_maxSpeed
public function setMaxSpeed($newMS)
{
$this->_maxSpeed = $newMS;
}
public function getMaxSpeed()
{
return $this->maxSpeed;
}
}
// Example
$car = new Car();
$car->setColor($dbInfo['color']);
$car->setMaxSpeed($dbInfo['maxSpeed']);
// Controller
class Sales
{
. . .
public function SaleCar(Costumer $costumer, Car $car, $quantity)
{
if($car->getColor() == "red") // Red is expensive color...
$car->MultiplyPriceBy(1.5); // Just an example...
else
$car->SubsetQuantityBy($quantity); // The car has quantity propery as well... and so on...
$costumer->setPaymentType("Credit-card");
. . .
$costumer->Pay($quantity * $car->getPrice());
return $finalPrice; // $quantity * $car->getPrice()
}
. . .
}
// View
class SalesPanel
{
. . .
public function output()
{
foreach($this->cars as $car)
{
if(in_array($car->getID(), $_POST['car_id']))
Sales->SaleCar(Costumer::GetCostumerFromID($_SESSION['uid']), $car, $_POST['quanityty']);
}
$output = . . .
$output .= "Car model GHi675 old by . . . "; // Get info from controller
}
. . .
}
?>
【讨论】: