Search code examples
perlcatalystdbix-class

How to create global var $schema for connection to DB in Catalyst app?


I've created a model lib/MyApp/Model/Foo.pm. Inside it:

...
sub bar {
  my $schema = MyApp::Schem->connect("dbi:SQLite:data.db");
}
...

It works fine but when I write so:

...
my $schema = MyApp::Schema->connect("dbi:SQLite:data.db");
sub bar {}
...

it doesn't work and write this:

Can't locate object method "connect" via package "MyApp::Schema" (perhaps you forgot to load "MyApp::Schema"?) at ...

I'd like to create global $schema var to use it in different methods. How can I reach it?


Solution

  • I read in Catalyst::Model::DBIC::Schema that we can us $self->schema to get access to db schema from anywhere. So this variant works fine:

    sub bar {
      my ($self) = @_;
      my $schema = $self->schema;
    }