Question about using global functions inside classes, I'm working on a MVC system.
The following method is part of a class it calls methods in the class such as the model and the view my question is I've got a global function in there called redirect() I've set it in a functions file that's loaded in my bootstrap file, as all controllers may need access to it, is this a bad practice or would I be best to make this a method of the controller class as all the controllers extend the parent controller.
public function post($slug){
if(!$slug){ redirect('blog'); }
$data = $this->model->getPost($slug);
$this->view->render('blog/single', $data);
}
Or would a static class make more sense? just seems a little over the top for a simple redirect function.
Global functions are not necessarily bad practice. There are two things to be aware of:
Naming: You should make sure that the name of the function avoids collisions and is obvious to what it relates. Your redirect function, it would be expected that it performs a request redirect. If instead your method related to something else more specific it would need to be clear that that is the case by prepending some contextual information.
State: Global functions should be stateless. This means the function should always provide the same result for the given input. If it does different things depending upon the time of day, the value of some variable, etc... Then generally this is bad. That may see like an obvious pitfall but there are more subtle versions of that problem. The obvious exception to this rule is actually requesting the time of day...
It looks like your code there obeys these two rules and so it is perfectly acceptable to do this.
Edit There is the testability issue, as you are referencing a global function that is required in by the class (or should be), you cannot mock this. For example in your redirect example you couldn't test the class properly without triggering the redirect function and you can't use a mock version of the function to detect that the real redirect method would have been called.
Using global function is bad practice, because it makes your classes untestable. You should put your desired methods to some object and pass it to classes as their dependency.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With