Where should I put my ajax call if I want to get some data from an external link or website? Should I put it in the controller, or in the service?


You should try to keep your controllers as "thin" as possible. That is, they should call other classes, which do the actual work.

The Craft approach is to keep most of your code in service classes, and if you're just starting out with plugin development, I recommend you follow this pattern.

Bear in mind, though, that your service classes define your plugin's API.

In other words, if you add a public method to one of your plugin service classes, you're essentially telling everyone "hey, you can use this method if you like".

If you're interested, I wrote a blog post about this a while back.

In summary, keeping your code in services is much better than keeping it in controllers, but don't treat your service classes as a dumping ground for everything.

  • If that's the case, what is the difference between service and controller? Apr 26 '17 at 6:08
  • Among many other things, controllers handle incoming HTTP requests. You should spend some time reading up on Craft plugin development, the underlying Yii framework, and the MVC pattern in general. StackExchange is not a substitute for independent study, and you need a solid understand of the basics. Apr 26 '17 at 6:13
  • No need to apologise, we're all learning. You're just going to struggle if you haven't taken the time to understand the basic concepts. Apr 26 '17 at 6:18
  • So the controller will be the one making the ajax call? correct me if I'm wrong sir :) Apr 26 '17 at 8:26
  • No, the service makes the call to the external API. The controller handles requests to your plugin. Apr 26 '17 at 14:21

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.