1

I created my own class file that I include in one of my Craft Services files. Is there any way I can access the craft instance inside of this file?

For example, inside my Craft service I create a new instance of my class like:

$wally = new Wally();

Inside of the actual Wally class file, I'd like to be able to create a variable in my constructor that gives me access to stuff like this:

craft()->elements->getCriteria(ElementType::Entry);

For further clarification:

class Wally {
   function __construct($craftInstance) {
      $this->craft = $craftInstance;
   }
}

If it sounds like I don't know what I'm doing, I probably don't. Any help would be appreciated. Using Craft 2.6 btw.

2

You don't need to pass anything in there.

The function craft() is just a public function that returns the static app. It does not matter if you call it inside a plugin or somewhere else.

namespace Craft; //<----- added namespace
class Wally {
   function __construct() {
      $criteria = craft()->elements->getCriteria(ElementType::Entry);
   }
}

If you don't want to be in the same namespace you can do

class Wally {
   function __construct() {
      $criteria = \Craft\craft()->elements->getCriteria(\Craft\ElementType::Entry);
   }
}

If you really want to save the app in an extra variable for whatever reasons you would do

new Wally(craft());
12
  • Well, the particular reason is I wrote some Hackalicious code that is going to have to wait to be refactored. This will definitely work! Thanks a lot. Mar 19 '18 at 20:50
  • Just a quick question. Wouldnt $criteria be, $this->criteria in the constructor? Just checking if this was intentional or not. Mar 20 '18 at 11:35
  • It depends what you are going to do. I don't know what you want or achieve. Mar 20 '18 at 11:41
  • Well, I ended up making an external class in a vendor file to handle a ton of the programming logic required in one of my Services files. The reason behind this was because I didn't want to clutter up my Service class file with a bunch of looping and traversal stuff. So basically, I queried my entry in the service, and ended up just passing that response off into my vendor class. However, I hit somewhat of a wall when I realized I needed to perform image transforms inside this class. I guess I was just trying to stay organized, but probably didnt go about it in the right way. Mar 20 '18 at 11:46
  • Dont really know why I didnt just do it all in the Service. Mar 20 '18 at 11:52

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.