How does MVC routing work?

前端 未结 2 1245
眼角桃花
眼角桃花 2020-12-07 18:10

So I\'ve started studying MVC (real MVC, not framework MVC) a bit more in-depth, and I\'m attempting to develop a small framework. I\'m working by reading other frameworks s

2条回答
  •  温柔的废话
    2020-12-07 18:31

    The router class, from my framework. The code tells the story:

    class Router
    {
      const default_action = 'index';
      const default_controller = 'index';
    
      protected $request = array();
    
      public function __construct( $url )
      {
        $this->SetRoute( $url ? $url : self::default_controller );
      }
    
      /*
      *  The magic gets transforms $router->action into $router->GetAction();
      */
      public function __get( $name )
      {
        if( method_exists( $this, 'Get' . $name ))
          return $this->{'Get' . $name}();
        else
          return null;
      }
    
      public function SetRoute( $route )
      {
        $route = rtrim( $route, '/' );
        $this->request = explode( '/', $route );
      }
    
      private function GetAction()
      {
        if( isset( $this->request[1] ))
          return $this->request[1];
        else
          return self::default_action;
      }
    
      private function GetParams()
      {
        if( count( $this->request ) > 2 )
          return array_slice ( $this->request, 2 );
        else
          return array();
      }
    
      private function GetPost()
      {
        return $_SERVER['REQUEST_METHOD'] == 'POST';
      }
    
      private function GetController()
      {
        if( isset( $this->request[0] ))
          return $this->request[0];
        else
          return self::default_controller;
      }
    
      private function GetRequest()
      {
        return $this->request;
      }
    

提交回复
热议问题