禁止子类调用受保护属性的方法

时间:2015-08-30 11:10:10

标签: php class oop inheritance encapsulation

我正在使用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
  }
}

那么您认为什么是实现这一目标的最佳方法?

1 个答案:

答案 0 :(得分:0)

忽略你的MVC结构是否是正确的软件设计,你可以通过只为他们需要的数据提供类来解决你的问题。例如,如果您希望View只能访问Model其属性,请不要以View作为参数实例化Model,但只能通过从ModelView的数据。