1

I'm working a PHP 5.5/MySQL web application.

If a class depends partly on some global GET and POST variables for its members, should I just refer to them directly from within the class, or should I have them as arguments in the constructor or some other initiating function?

class myclass {
  protected $id;
  public function __construct() {
    $this->id = (int)$_GET['id'];
  }
}
$myclass = new myclass();

Or

class myclass {
  protected $id;
  public function __construct($id) {
    $this->id = (int)$id;
  }
}
$myclass = new myclass($_GET['id']);

How do MVC frameworks handle this issue?

1

Another important point is unit testing. If you inject the dependencies of a class, you can easily instantiate them in unit tests.

You might want to look at Misko Hevery's clean code talk about global state (He has few other good talks about OOD)

0

The whole point of DI is to make your functions independent from the Environment, namely the Global variables. That means:

function bad () {
    $id = $_GET['id'];
    ...

Is as Bad as:

function bad () {
    global $db;
    ...

In both examples you need to pass the function/method dependencies via function arguments. To understand it better imagine if at some point you needed to create an instance of the class, but when you don't have the id in the query string. Another example is if you later decided to implement the same functionality via POST as well. So you need to go and replace all of those $_GET variables with $_REQUEST.

So if I were you I'd definitely go for the second approach. Also it is not related to MVC design-pattern at all. Different frameworks might suggest different practices or don't suggest anything at all.

  • You have to put $_GET['id'] somewhere, though. Should it be outside of all classes, in a functional area of the code? Or should there be a class whose sole purpose is to take globals into itself and instantiate objects of other classes based on them? – Buttle Butkus Apr 27 '14 at 20:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.