Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to understand why Laravel's many static methods is not considered bad practice [closed]

Tags:

php

laravel

I'm pretty confused.

I've asked a few developers on Reddit to review my codes. It looks like this.

Template::load('register', array('error_message' => Language::translate('username_in_use'));

So it loads register.php, replaces {error_message} with translation. (Sorry, this username is in use. Please pick another.)

They said using too many static calls is a bad practise. Yet they suggest Laravel framework, which completely gets rid of $this and uses static calls.

Can someone explain me how come if this is bad practise, Laravel being a classy framework?

like image 861
Lisa Miskovsky Avatar asked Feb 26 '13 03:02

Lisa Miskovsky


1 Answers

Static state is omnipresent and entirely destroys testability since you can't just reset the state. Additionally, anything could affect the state in ways that other aspects of the code can't predict, resulting in the potential for wildly unpredictable behavior.

Laravel 4 prevents this by using static 'facades'. These facades are "syntactic short-hand for IoC resolution". They provide both syntactic sugar and prevent tightly coupled code.

The classes that are resolved by the facades can be changed and allow you to inject mock systems or whatever you wish.

Of course, this doesn't really solve the other aspect of static access.. Which is that you can't just inject different functionality. But, with Laravel applications you generally don't have facade use within your domain. It's more for the web transport layer, where it's very helpful since the web transport layer is already tightly coupled with your framework, this just makes good use of that fact by creating something sort of akin to a DSL for that layer of your application.

I repeat, please consider not using facades deep in your domain layer.

like image 76
Shawn McCool Avatar answered Sep 22 '22 01:09

Shawn McCool