I've a helper class in Laravel 5.1 with static methods for calculating week numbers, dates in weeks, etc. (Why static? I need max. 1 instance of this helper class)

I need this logic in my views. I'm using MVC pattern. My question is quite simple:

  • May my view call the helper methods directly?
  • Or: is my controller responsible to call the helper and pass the results to the view?
  • 1
    A view should definitely not concern itself with backend logic. A view should not even be aware of these things. The Controller is what passes the results to the view, yes. Now whether you should have business logic in your Controller, that's another question. – Alternatex Dec 2 '15 at 16:52
  • @Alternatex Thanks. Is it "business logic" to get manipulated data from a helper and pass it to a view? Controller has the responsibility to delegate and to consolidate, not? – schellingerht Dec 2 '15 at 17:40
  • 1
    Yes, you are correct. I may have misunderstood your last sentence. It's definitely not business logic to pass the results from the helper to the view. – Alternatex Dec 2 '15 at 19:36

Having static methods because you only need one instance is an awful excuse. You are introducing global state, which is bad and messes up unit testing.

If you really need only one instance of the helper, make a container with a method like createAndReturnHelper which will act as a weak singleton, lazy loading the class if it is not preset and/or otherwise returning the already created instance. If you need the helper in your controller, be sure to inject it by using the container to obtain the helper from it.

That gets your static methods sorted out.

Whether you want the view to call helper's methods directly or not, that is mostly up to you, although it has proven to me that the better approach is to do all the logic inside the controller, filtering data, finding the right stuff, and include into the view only very simple PHP, such as the foreach loop and variables, of course. Variables, which contain the correct data.

The main point into making the view not contain any complicated php code is that frontend designers usually do not have deep knowledge of the programming language(s), and they are not really supposed to, they are focusing on frontend, so you can tell them if you iterate over the variable $x, it will contain all the data you need. The backend team will make sure the data is correct, so just style it for the end user in a nice way.

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.