PHP控制器。 服务页面和表单之间的关注点分离[关闭]

I know there is a lot of debate about which PHP framework is the best and this isn't a thread about this ;). This thread is about how do developers handle the separation of concerns belonging to a controller.

In MVC-ish framework, the controller will serve pages (get) and accept form submission (post). However, I found that even trivial controller can be hard to understand.

With the following CodeIgniter example:

 class TrivialController extends MY_CONTROLLER{

         public function login(){
           //Load a view containing a login form
         }

         public function login_p(){
           //Load user model + login
           //Success / Faillure view
         }

    }

or

class TrivialController extends MY_CONTROLLER{

         public function login(){

              if(GET){
                  //Load a view containing a login form
              } else if (POST) {
                 //Load user model + login
                 //Success / Faillure view
              }

         }
    }

I found both option to be equally cumbersome:

  • Option 1: Two methods with the same name, for the same feature. It'll make the controller harder to read.
  • Option 2: A method driven by a big if-else on the request type. It'll make the method harder to read.

So, here's the question. How do you handle this in practice?

The GET/POST are two different, yet functionally cohesive things.

This is a very common workflow in web applications:

  • A GET request is made, which triggers a query to construct a form
  • A POST request is made, which is
    • A) Validated and a command is executed. Sequentially, the client is redirected to as success page.
    • B) Failed the validation. Sequentially, the client is redirected to failure page (most likely the GET page).

I consider these to be different enough to split the into different methods, but similar enough to keep in the same controller.

The problem is the naming convention. You should concisely distinguish between command and query actions, and make use of object-verb names that describe the subject what you are working with, and what you are doing with it.

class TrivialController extends MY_CONTROLLER{

     public function askCredentials(){
       // Show login form
     }

     public function verifyCredentials(){
       // Login
     }

}