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 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题