Let me first just say that you do not need to do any metaprogramming for this. Metaprogramming should only be reached for when there is just simply no other way, it is not a tool for everyday use. In this case you can solve your problem with simple built in Moose features like lazy, default, build or lazy_build as several other posters have stated already.

1) Is there some way to access $self in the scenario described above?

I would suggest you use lazy with some combination of default or builder. metaperl above pointed to the relevant Recipe for this. In both the default and builder you will get a reference to $self as your first argument.

I would likely recommend builder here since it would then treat the initializer as a method and so your subclasses can then take advantage of it. If this is not the desired behavior then you can use default.

2) Is there perhaps a better/more elegant approach to achieve the above?

No, what you have going looks fine to me. I would recommend that you do not store your default code refs in the package since they will be interpreted as methods by Moose. If that is what you want, then I suspect you should change from default to builder.

3) Currently i am providing the DB handle to objects that need it via the SQLConnection role. I am not sure this is the best solution.

We do something very similar at work with a WithDBICSchema role that provides access to the DBIx::Class schema object. It is a perfectly fine approach and is of the more common role usage patterns out there.

-stvn

In reply to Re: Moose, SQL and initialization via Moose::Meta::Attribute by stvn
in thread Moose, SQL and initialization via Moose::Meta::Attribute by ZAmonk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.