dongpu1881 2018-02-18 09:56
浏览 201
已采纳

要求parent :: __ construct()的最优雅方式

Say I have the following controller structure:

class Controller {

    public function __construct(){
       $this->accessControl();
    }
}

class Account extends Controller {

   public function __construct(User $user){

      parent::__construct();
      $this->user = $user;
   }
}

How to require other devs to explicitly call parent::__construct() in their child controllers? It contains critical stuff like access control etc

So far I decided to wrap all functions from parent constructor into init() method which sets initialized property to TRUE, then check this property in the router. If it's not TRUE - throw an exceptions.

public $initialized = false;

class Controller {

    public function __construct(){
       $this->init();
    }
}

protected function init(){
   $this->accessControl();
   $this->initialized = true;
}

class Router {
    public function process($path){
       $controller = new User();
       if(!$controller instanceof Controller || !$controller->initialized){
          throw new Exception('Error');
       }
    }
}

Does it smell bad?

  • 写回答

2条回答 默认 最新

  • doutuzhuohao6449 2018-02-18 12:26
    关注

    The same is needed in Symfony\Console Command, where constructor has to add command name and definition.

    They handle it like this in single place where the command is added. So your approach to check controller in Router is the same. I'd got for it, rather then put the responsibility to abstract Controller or some reflection.


    On the other hand, it looks accessControl() should be checked on security layer level and not in router.

    What framework do you use?

    Could you decouple it from router by using EventSubscriber and framework event?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题