3

It seems that something like

craft()->urlManager->setRouteVariables(array('calupdateResponse' => $out));

works in a Controller so that {{ calupdateResponse }} has a value, but it doesn't work in a function in a plugin's Services (no error, just no values show up in twig).

I'm wishing that a single function in Services can output a number of variables to twig for templating. What is the most straightforward way? Is it necessary to create a function for each one in PluginVariables.php? Then I have many functions instead of just one. This is for a CP page, if that makes a difference.

On a related note, is it possible for twig to instantiate a plugin's model, with access to all it's properties?

Thank you!

4

Services are not meant for rendering templates, but for business logic, saving data, and retrieving data. The setRouteVariables method should only be used in a controller to send some information to a variable.

You can use a controller to reach out to a service for some data, then use the controller to report that data back to the view for display using the setRouteVariables function. You can skirt around this by using Variables to directly call services, using a separate variable for each service function.

On a related note, is it possible for twig to instantiate a plugin's model, with access to all it's properties?

Not directly, and this shouldn't be done. It is best practice to not have views directly instantiating models, but to have controllers and services act as the middle-men. It will help keep your code testable, reusable, and readable.

From the Craft documentation:

Controllers

Generally speaking, controllers are the middlemen between the front end of the CP/website and your plugin’s services. They contain action methods which handle individual tasks.

Services

All of your plugin’s business logic should go in services, including saving data, retrieving data, etc. They provide APIs that your controllers, template variables, and other plugins can interact with.

|improve this answer|||||
  • Thank you, this is helpful. To clarify then, for a calendar plugin, the routines to produce a full calendar or a mini calendar should be happening in an action method in a controller, rather than in services? – kr37 Jun 14 '15 at 4:15
  • Correct. Of course, there are always exceptions, but the answer above is a good best practice guideline. – Aaron Berkowitz Jun 14 '15 at 14:42

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.