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.
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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |