doxn43207 2015-08-30 11:10
浏览 81

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

I'm developing application using MVC concept and want to restrict the View class from calling methods of model but give it access to model's properties so it can just get data when it needs it. Instead i want to give the Controller class ability to call model's methods(and if possible restrict it from accessing properties cause it really doesn't need to do so).
My question is how do i design classes relationship to achieve that goal or can i just somehow tell php to disallow that class calling methods of another?
Currently relations of my classes look like this:
Controller

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

}

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

}

And there are other classes which are inheriting from Controller and View class, like:

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

and

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

So what do you suggest as the best method of achieving this?

  • 写回答

1条回答 默认 最新

  • dqyknf4423 2015-08-30 11:16
    关注

    Ignoring whether you MVC structure is proper software design, you can solve your problem by feeding classes with only the data they need. For example, if you want your View to only have access to Model its properties, don't instantiate View with Model as an argument, but only pass the data from Model to View.

    评论

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测