Coding PHP Applications for the Command Line

When writing a PHP application, avoid explicitly using the special variables, like $_GET, $_POST, and $_SESSION in your internal classes, so that you can more easily test the class outside of a web environment – specifically, from the command line. When you run a PHP script from a web page, you So instead of:

class ShowRecordController {
    public function __construct() {
        ....
    }

    public function run() {
        if ($_REQUEST['method'] == ... ) {
        }
        ....
    }
}

You can pass in the parameters to the constructor:

class ShowRecordController {
    protected $request;
    public function __construct($request) {
       $this->request = $request;
        ....
    }

    public function run() {
        if ($this->request['method'] == ... ) {
        }
        ....
    }
}

This will make it easier to test your application on the command line, and will also make it easier to re-use the classes you have written.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top