top | item 5047484

(no title)

stormpat | 13 years ago

The problem with static and singletons have been adressed by the creator, Taylor Otwell. Heres a quote (http://forums.laravel.io/viewtopic.php?pid=3237)from him regarding the static methods in laravel 4.

"Yeah, this [static methods/singletons] is something I have thought about a lot.

I have gone from everything totally static, to everything totally dependency injected, to somewhere in between. The criticisms of static methods are certainly valid. If you'll notice in the Laravel core code, the router, session handling, and database stuff is actually pretty thoroughly dependency injected. When the Laravel core creates the session payload, it injects the driver. That allows me to unit test the framework more thoroughly since I can inject mocks and stubs.

Problems I have run into with using DI throughout the framework is that you start to fight against the global state that exists within PHP itself. For instance, functions like "file_get_contents" and "file_exists"... you have to have some way to mock those.

I have actually moved Laravel totally off of static methods before to see what it would be like, and it's not too bad. I think in the future it's possible more classes will be moved off of static methods.

To dig deeper into Laravel, there is actually an abstract "Facade" class that makes you think a class is static when it's not. For instance, when you do "Session::get", you are actually hitting the Laravel\Facades\Session class, which is resolving the session payload out of the IoC container and then calling the method you want. It's a trick to give you convenient access while still keeping the framework somewhat testable.

So, I totally agree with the articles. The struggle so far has just been to find a good balance point for Laravel. Writing testable code is still up to the developer to an extent. You can use the IoC container to inject a database connection instead of just using the DB static methods. However, things like the Input, URL, File, etc. classes still being static could lead to some testability problems. I've broken encapsulation on the Input class just to make it a little more testable. You can set the Input just by saying "Input::$input = array()".

This is probably way more information than you wanted, but just letting you know this is something I have thought about a lot. Symfony2 has probably done the best job of keeping things testable that I know of. I think Laravel's testability is decent as it stands, but I know there are things that could make it better."

discuss

order

camus|13 years ago

file_get_contents is an interesting one , it creates variables out of thin air ( though i think the scope stays "local") when called from a function.

fooyc|13 years ago

file_get_contents only returns the content of the given file; you must be speaking about something else