srchulo
srchulo

Reputation: 5203

catalyst require lib across whole application

So I have a .lib file with some of my own subroutines in it that I would like to make available to the entire Catalyst app. Right now I require the file in lib/myapp.pm and I have no issues. However, whenever I try to call that subroutine in a controller, I get this error:

"Undefined subroutine &myapp::Controller::Root::my_sub called at 
/home/user/myapp/lib/myapp/Controller/Root.pm line 35, <DATA> line 1003."

If I require the file I want to require in the controller, that gives me no issues. However, I would prefer to have to only load it in one place for the whole application if this was possible. Also, if I require the file within the controller, does that mean that this file is being loaded every time a request is made? (I'm using mod_perl if that makes any difference). I'd like to make this as efficient in terms of the file being loaded once for the whole app and any requests, but also loaded only in one place just for the sake of clean code. Thanks!

Upvotes: 0

Views: 104

Answers (2)

ikegami
ikegami

Reputation: 386541

use myapp;

is basically

BEGIN {
   require myapp;
   import myapp;
}

require myapp; executes myapp.pm if it hasn't already been executed. In other words, no matter how many times you do use myapp; in a process, the file will only be executed ("loaded") once.

import myapp; calls myapp::import() if it exists in order to export stuff. Assuming myapp exports my_sub, this is why your code isn't working.

You have two options.

  1. Call the mysub in the myapp package: myapp::my_sub(...).
  2. Use use myapp; to create a local name for my_sub in every package you call my_sub so you can call it using just my_sub(...). (This assusmes myapp exports my_sub.)

Upvotes: 2

pmakholm
pmakholm

Reputation: 1568

The command use myapp; will only load your myapp.pm file once, even when called multiple times. But each time it will call the import routine makes my_sub() available (Assuming you export it using Exporter or something else) without having to write myapp::my_sub().

Upvotes: -1

Related Questions