Search code examples
perlmoose

How do you use MooseX::Declare with a subclass of Moose?


Let's say you've done something like the extending recipe 3 or 4. So you have some class like MyApp::UseMyBase that you can use in place of 'use Moose;' in your normal Moose-using code. But how do you use MyApp::UseMyBase when using MooseX::Declare?

I can see MooseX::Declare::Syntax::MooseSetup::import_symbols_from() which might be promising, but have no idea how to change its return value and have MooseX::Declare use and import from MyApp::UseMyBase instead of Moose.


Solution

  • You'll have to subclass MooseX::Declare::Syntax::Keyword::Class, and possibly also MooseX::Declare::Syntax::Keyword::Role, if that's what you want, and customise import_symbols_from in there.

    Then you extend MooseX::Declare itself to actually provide your modified keywords. For that, you'll need to customise the keywords method. You can either replace the ClassKeyword and RoleKeyword instances returned by it with instances of your customised keywords, or just make it set up the new keywords under a different identifier, depending on whether you want

    use MyMooseX::Declare;
    class Foo { ... } # the modified class keyword
    

    or

    use MyMooseX::Declare;
    class   Foo { ... } # the default class keyword
    myclass Bar { ... } # the modified class keyword
    

    CatalystX::Declare contains prior art in doing this, but it's also much more complicated than what you're asking for. I'm not aware of a simpler example of this, but I'd love to include improved documentation on this in case you're feeling like sharing your solution with the rest of the world