ZF 2.4 - controller - alternative for init()? - zend-framework2

I've this two lines on all the action() in the controller so I want to move it to init() so it will get called each time. It doesn't work so I tried __construct and it won't work as it says "PHP Fatal error: Uncaught Error: Call to a member function get() on null"
Maybe that can be done in factory and you still call getServiceLocator in factory class? If I can do it within controller that will be even better as that's less step to do and is that possible to do it in controller so every action will have that?
$view_helper = $this->getServiceLocator()->get('viewhelpermanager');
$view_helper->get('headScript')->appendFile(....);

Only two solutions exist:
You can do an abstract controller, and use the viewhelpermanager as dependency in your constructor. This means you will need to pass the viewhelpermanager in all the subclasses factories and not forget to call the parent construct and so on when creating the object.
You can use a delegator in the service manager and an abstract controller that contains a setViewHelperManager method and a viewhelpermanager (or worst, a trait :) and a ViewHelperManagerAwareInterface and an initializer), and do a "soft dependency", but that's a wrong way to do things in terms of maintenance (code readability).

Why don't you write your own view helper and make that include the js file(s). You can then use this in all the view.phtml files that require these files. If you need to change/add/remove js files then just do this in your view helper, obviously this change will reflect in all your views that use it.
This keeps the view stuff away from your controller.
Hope this helps.

Related

Why controller action should call one model method other than an initial find or new?

I have almost all of the "shared" statements in functions in my model. The problem is that I am getting the following error, when I need to use more then one of these functions in my controller:
Controller action should call one model method other than an initial
find or new
and the IDE goes deeper explaining that:
This inspection warns if a controller action contains more than one
model method call, after the initial .find or .new. It’s recommended
that you implement all business logic inside the model class, and use
a single method to access it.
Is this mean that all of the logic should be put in more complex model functions? I have thought that the work of the controller is to call model functions and passes the results to the view.
If I put back the model functions code back to the controller, everything will work, but I will get a code duplication in all my controller actions.
So, what is the right approach here?
The warning message indeed means that the logic should be put in a single model function, but not necessarily more complex ones. To avoid model duplication and/or the "fat model" problem, you may need to introduce additional classes that the model relies on.
Yes, the work of the control is to call model functions, but only as a thin veneer, per this inspection guideline of one model function per controller action aside from an initial create/find.
I'm not sure I understand your comment about getting code duplication in your controller if you move functions back up, since you can always introduce shared functions at the controller level. But again, that's not the recommended approach of "thin controller" and "reasonably thin model" with supporting classes as required.

Where to put needed initialization code when using Dependency Injection?

When my constructors are pure arguments-to-propeties setters then I'm not sure where to put other code that a class needs to properly work.
For example in JavaScript I'm programming a WindowMessageController that processes message events on the window object.
In order for this to work, I must somewhere attach the handler:
var controller = this;
this.applicableWindow.addEventListener("message", function(event) {
controller.messageAction(event.data);
}
Where does this stuff correctly belongs?
in the constructor
in the .initialize() method - introduces temporal coupling
in the WindowMessageControllerFactory.create(applicableWindow) - quite a distant place for so central piece of code. This means that even such a small class would be split into two pieces.
in the composition root itself - this would multiply its size when doing all the time
in some other class WindowMessageRouter that would have only one method, the constructor, with this code
EDIT
This case seems special because there is usually only one instance of such a controller in an app. However in more generalized case what would be the answer if I was creating an instances of Button class that would wrap over some DOM <button /> element? Suddeny a
button = buttonFactory.create(domButtonEl);
seems much more useful.
Do not put any real work into constructors. Constructors are hardly mockable. Remember, seams aka methods are mockable. Constructor are not mockable because inheritance and mocking.
Initialize is a forbidden word, to much general.
Maybe, but you can implement factory as a static method of class too, if you are scared of many classes ,)
Composition root is just an ordinary factory. Except it is only one, because your app probably have just one entry point ,)
Common, we are using Javascript. If you need just one factory method, why you need class for it? Remember, functions are first class objects.
And for edit. There is nothing special on singetons, unless they do NOT control own lifecycle.
Golden rule: Always (almost ,) do separation between app wiring and app logic. Factories are wiring. Just wiring, no logic, therefore nothing to test.
I would place this code into initialize(window) method but this method cannot be part of WindowMessageController's public API - it must be visible and called by direct users (so composition root and tests) only.
So when DI container is returning WindowMessageController instance then it is container's responsibility that initialize method has been called.
Reply to EDIT: Yes, this factory seems to be the best way for me. Btw. don't forget that the factory should probably have a dispose method (i.e. unbinds the event handler in case of button)...
I think you need to create a Router class that will be responsible for events distribution. This Router should subscribe to all the events and distribute them among the controllers. It can use some kind of the message-controller map, injected into constructor.

Why are Controller Constructors fired before the Initialize method

I have a base Controller ApplicationController that needs to grab the URL Host and do some processing before the child controllers are fired. Since controller constructors are fired before RequestContext is initialized I have to override Initialize method to do my processing.
ApplicationController:
Protected Overrides Sub Initialize(ByVal requestContext As System.Web.Routing.RequestContext)
MyBase.Initialize(requestContext)
Dim host as String
host = Request.Url.Host.ToString
End Sub
What is the logic behind having Controller Constructors fire before the Initialize method?
Also what are the rules to what should be placed in the Initialize Method.
Assuming that constructors are the first instance method ever to be fired in a .NET class, that shouldn't come as a surprise and is not really something MVC specific. It's more how the .NET framework works.
The MVC framework needs to first instantiate a controller and then initialize it => it calls the constructor first. And because performing lots of code that could potentially might throw exceptions, etc... is not always best to be put in a constructor => the presence of the Initialize method. As far as this method is concerned I must admit that I have written lots of ASP.NET MVC code and never had to use it. Action filters always seemed like a better alternative.
So to answer your question:
Also what are the rules to what should be placed in the Initialize Method.
I've never ever put any code and never ever need to override this method. I've always preferred using action filters because this way I am no longer in the obligation of deriving from a common base controller (not that this is a problem).
Sometimes, maybe you would want your request to initialize your variables, so in this case you should use the Initialize method.
For example, if you want to initialize some variables in a different way when the request is local or not, etc.

If I have a function that I use both in the controller and in the views, where should I put it?

I try to be very good about keeping my view code and my controller code separate, but occasionally I run into situations where I need to use the same function in the controller and in the views. Where should I put this function so that I can access it from both the controller and the view?
You can put it in a controller and make it available as a helper. If you need it to be available between multiple controllers and their views put in the application controller or other inherited controller:
helper_method :shared_function
According to your situation, for example if the function return a standard Variable value that don't require any controls, you can call it directly from the view, on the contrary, if you have a function that return for example an array that requires controls it's judicious to call it from the the model before you show what you want on the view.
I actually think a module is the best way to share code amongst controllers. Helpers are good if you want to share code amongst views. Helpers are basically glorified modules, so if you don't need view level access, I suggest placing a module in your lib folder.
If the code is really a set of utilities that doesn't need access to object state, I would consider putting it in a module to be called separately.
If the code needs state and is used in a subset of all controllers that are not very closely related, put it in a module and include it in necessary controllers.

call a helper from another view

I know that if I want to call a helper of another controller, I can do something like:
helper :other_controllers
But I was wondering why I can't do something like OtherControllersHelper.method inside the view?
Due to the way that Rails loads your modules, you cannot do this without modification.
Rails includes the associated helper models into the ActionView::Base instance used to render a template. ActionController::Helpers#helper (used in the example above) adds more helper modules to the list of those to be included. The helper methods that are used in views are written as instance methods. Modules in Ruby do not provide any good ways of getting at instance methods without using a constructor. Which is one of the big things that separates modules from classes.
To access your helpers from another controller with just OtherControllersHelper.method, you will need to redefine method as a class method. However, redefining those methods as class methods would make them inaccessible from your views.
You could duplicate all instance methods in your helpers as class methods, but that's definitely not a better solution that adding helper :other_controllers. There are ways to define wrappers pragmatically, but again, it's not the best way to handle the situation.
If you've got a lot of helpers that are likely to be used in multiple controllers/views maybe you're better off putting them somewhere else. Somewhere like app/helpers/application_helper.rb. Or another helper module that could be loaded only in the controllers that need it.

Resources