2

This feels like it falls under silly/obvious questions, but I can't seem to find a decent answer anywhere, so I'm asking here:

How do I find out which methods for example, is available on an object? For example, I'm able to do {{ entry.authors.one() }} and get the first one in the object. Great, but if I didn't kow that one() existed, how would I find out? Now, in regular ol' PHP I'd var_dump($authors) or whatever, and whatever the object contained would be displayed, including methods. Doing the same in a twig template by either using {{ dump(entry.authors() }} or {{ dd(entry.authors() }} shows the object (I think?) but not the methods I'm able to use on it. In fact, it seems impossible to just look up what specific methods I'm able to use on a specific object. I'm sure that I'm just missing something though.

So how can I find out what I'm able to do with said object? Surely there must be a better way to know other than "you'll have to guess" or rely on abstract documentation which might not be relevant to a specific use case?

I realize the above example is incredibly simple, but obviously there are more complex situations that arise. Like when I'm digging down into multiple nested fields, looping through their children() etc, it's quite easy to get "lost", as it were.

1 Answer 1

3

This bothered me too until I switched to PHPStorm and started using this: https://github.com/nystudio107/craft-autocomplete.

If that's not an option and you fancy extending Twig, you can use php's get_class_methods function to return the methods of a passed-in object.

Ultimately though, given the deep inheritance tree from Yii's base objects, listing out 100s of methods that you'll mostly never touch is not all that helpful, I find. When you need to do something complicated, you're best off digging through the Class Reference - at least you'll get descriptions of what the methods do, and their parameters.

(Related, I often use the |keys filter to dump out an object's properties.)

2
  • I'm not sure how to extend twig like that. I just might take the plunge and switch to phpstorm, even though I love how my VScode is set up now. Feb 28 at 10:05
  • 1
    If you wanted to explore extending Twig, just head to pluginfactory.io and tick the box for Twig Extensions - it'll generate all the plugin scaffolding for you to create your own Twig filters or functions. Then inside your function/filter you'd return get_class_methods($object); and that's about it! Feb 28 at 10:45

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.