Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create subroutines in package on 'use base'?

I'm attempting to create a small ORM library for use in a Mojolicious web-application. I've grown very fond of Ruby's Datamapper library and would like to emulate some of its behaviour if possible.

In Datamapper you can mixin Resource, and then have methods added to your class such as 'all', etc:

# User.rb
class User
    include Datamapper::Resource;
end
...

# Application.rb
users = User.all

For my library I'm attempting to add some package level functionality to modules that inherit from a base Model in order to achieve a similar behaviour.

In essence, I would like to be able to do something approximating the following:

# User.pm
package User;
use base Model;
...

# Application.pm
my @users = User::all();

I've had a look around for examples of meta-programming in perl and haven't found anything immediately helpful.

What I'm after is the following:

  • Alternate perl patterns that achieve similar elegance in a more idiomatic fashion
  • Ability to inherit subroutines on the package level, as well as the object level
  • Ability to execute code on 'use' in the scope of the current package, or
  • Have the current package passed to code that is executed on 'use'
  • A guide to meta-programming in Perl
  • A existing declarative ORM library that supports easily creating mock-adapters as well as DB2, and MySQL

Ideally I would like to avoid running eval on large strings as much as possible.

Any help would be greatly appreciated :-)

like image 303
Lyndon Maydwell Avatar asked Dec 06 '25 10:12

Lyndon Maydwell


1 Answers

Alternate perl patterns that achieve similar elegance in a more idiomatic fashion

Roles surpass mixins.

Ability to inherit subroutines on the package level, as well as the object level

Roles are normally consumed on the package level, but with trickery also can be applied to an instance only. (FIXME how?)

Ability to execute code on 'use' in the scope of the current package

import

Have the current package passed to code that is executed on 'use'

All parameters on the use statement are passed into import as arguments.

A guide to meta-programming in Perl

Moose::Manual, Moose::Cookbook

A existing declarative ORM library that supports easily creating mock-adapters as well as DB2, and MySQL

DBIx::Class

like image 125
2 revsdaxim Avatar answered Dec 09 '25 00:12

2 revsdaxim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!