在Controller或Model中存储变量的最佳实践是什么? 例如,当脚本被执行时。它从会话中获取用户ID并获取它的用户类型,超级管理员,管理员,服务代表,销售代表。我们还检查用户ID所属的帐户,并获取该帐户的所有设置。
我的问题是我在控制器或模型中存储这些值的位置?
提前谢谢。
答案 0 :(得分:3)
在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数据流以这种方式工作:
答案 1 :(得分:0)
您将它们存储在模型中(从数据库中抓取它们),然后使用控制器(在页面加载时)将它们拉出来,然后在视图中显示它们的结果(通过在需要时调用控制器类)。
这是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
}
. . .
}
&GT;