[Dbix-class] Where to define constants.
Ian
dbix-class at iandocherty.com
Sat Apr 24 09:34:51 GMT 2010
Bill
Yes, I have pondered the same question.
My current solution is to have a MooseX::Singleton class that defines
all constants used in my database (and perhaps elsewhere in my
application). e.g.
package MyApp::Constants;
use MooseX::Singleton;
has track_type_foo => (is => 'ro', default = 1);
has track_type_bar => (is => 'ro', default = 2);
----
Then, as per Moosex::Singeton I initialize it once at the start of my
application.
MyApp::Constant->initialize;
----
Then I can use it throughout my application.
my $constant = MyApp::Constant->instance;
sub foo_track_type_count {
return shift->tracks( {
track_type => $constant->track_type_foo,
})->count;
}
----
regards
Ian
On 23/04/2010 22:46, Bill Moseley wrote:
>
> My music DB has CDs and each CD has many tracks.
>
> In my CD source class I have helper methods.
>
> sub total_track_count {
> return shift->tracks->count;
> }
>
>
> And for the sake of the example, I have a "track_type".
>
> sub foo_track_type_count {
> return shift->tracks( { track_type => 1 } )->count;
> }
>
> sub bar_track_type_count {
> return shift->tracks( { track_type => { -in => [2,3] } } )->count;
> }
>
>
> I'm finding I need to know the track_type IDs in other code -- for
> example, in validation code. I don't want to hard-code the track_type
> ids all over the place. My question is how do you manage constants like
> this?
>
> One option is to have a constants module, i.e. "use MyApp::Const
> 'track_types'" that my result source uses. Then any other code that
> needs those constants also uses MyApp::Const.
>
> Another option would be to define the constants in the Track source.
>
> sub bar_types { return [2,3] }
>
>
> then back in the Cd class:
>
> sub bar_track_type_count {
> my $self = shift;
>
> my $bar_types = $self->result_source->schema->resultset( 'Track'
> )->result_class->bar_types;
>
> return $self->tracks( { track_type => { -in => $bar_types } }
> )->count;
> }
>
>
> How do you manage constants like this?
>
> BTW -- Can't I get the result class w/o building a resultset? Something
> like $schema->source( 'Track') ?
>
>
>
>
>
> --
> Bill Moseley
> moseley at hank.org <mailto:moseley at hank.org>
>
>
>
> _______________________________________________
> List: http://lists.scsys.co.uk/cgi-bin/mailman/listinfo/dbix-class
> IRC: irc.perl.org#dbix-class
> SVN: http://dev.catalyst.perl.org/repos/bast/DBIx-Class/
> Searchable Archive: http://www.grokbase.com/group/dbix-class@lists.scsys.co.uk
More information about the DBIx-Class
mailing list