禁止子类调用protected属性的方法


Disallow subclass to call methods of protected property

我正在使用MVC概念开发应用程序,并希望限制视图类调用模型的方法,但给它访问模型的属性,以便它可以在需要时获取数据。相反,我想给控制器类调用模型的方法的能力(如果可能的话,限制它访问属性,因为它真的不需要这样做)。
我的问题是,我如何设计类的关系来实现这一目标,或者我可以告诉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;
  }
}
<<p> 视图/strong>
class View
{
  protected $_model; //has access to model so it can get model's properties when needed
  public function __construct($model)
  {
    $this->_model = $model;
  }
}

还有其他继承自控制器和视图类的类,比如:

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
  }
}

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

忽略MVC结构是否是适当的软件设计,您可以通过仅向类提供所需的数据来解决问题。例如,如果你想让View只访问Model的属性,不要用Model作为参数实例化View,而只将Model的数据传递给View