我正在使用MVC概念开发应用程序,并希望限制View类调用模型的方法,但是可以访问模型的属性,以便它可以在需要时获取数据。相反,我想让Controller类能够调用模型的方法(如果可能的话,限制它访问属性,因为它确实不需要这样做)。
我的问题是我如何设计类关系来实现这个目标,或者我可以以某种方式告诉php禁止该类调用另一个类的方法?
目前我班级的关系如下:
的控制器
class Controller
{
protected $_model; //has access to model so it can call model's methods to modify it
protected $_view;
public function __construct($model, $view)
{
$this->_model = $model;
$this->_view = $view;
}
}
查看
class View
{
protected $_model; //has access to model so it can get model's properties when needed
public function __construct($model)
{
$this->_model = $model;
}
}
还有其他类继承自Controller和View类,如:
class UserController extends Controller
{
public function modifyData()
{
$this->_model->modifyX(1); //this works and it should be working because i need the controller to be able to call model's methods
$someVar = $this->_model->x; //this works and it should not be working because i don't need the controller to be able to get model's properties
}
}
和
class UserView extends View
{
public function getData()
{
$this->_model->modifyX(1); //this works and it should not be working because i don't need the view to be able to call model's methods
$someVar = $this->_model->x; //this works and it should be working because i do need the view to be able to get model's properties
}
}
那么您认为什么是实现这一目标的最佳方法?
答案 0 :(得分:0)
忽略你的MVC结构是否是正确的软件设计,你可以通过只为他们需要的数据提供类来解决你的问题。例如,如果您希望View
只能访问Model
其属性,请不要以View
作为参数实例化Model
,但只能通过从Model
到View
的数据。