Where to put initialization code (connecting to databases, generating stuff, loading data files, etc)?

Here are some existing options:

  1. Put it into the module in question. This will execute the code in BEGIN{} when the module is used.

    (+) Good encapsulation.

    (-) Everything is tied to databases, configuration, specific file locations etc. Hard to isolate unit tests, even harder to run code snippets to find bugs, as in perl -MFoo -d -we 'Foo->new'

  2. Put it into separate script (startup.pl etc)

    (-) Code away from where it's used, easy to forget something.

    (-) Initializing all-or-nothing.

  3. startup() (or other name) routine in every module in project.

    (-) still easy to forget to run it.

  4. Use Perl's built in INIT{} block. Here's the problem (same for Apache, of course):
    bash$ plackup -e 'use warnings; INIT{ warn "foo"; }; sub { warn "here +"; return [200, [], []] };' Too late to run INIT block at (eval 7) line 1. HTTP::Server::PSGI: Accepting connections at http://0:5000/ here at (eval 7) line 1. 127.0.0.1 - - [20/Nov/2014:14:18:08 +0200] "GET / HTTP/1.1" 200 - "-" + "Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:33.0) Gecko/20100101 Firef +ox/33.0"

    Note the Too late to call INIT warning and no sign of "foo" in output.

Now I'd like to have a module which is used as follows:

In project's module:

use Init::Queue sub { get_dbh(); load_file(); build_cache(); }; # postpone till explicitly called

In production/initialization code:

Init::Queue->startup(); # this executes all startup blocks, # in order of appearance

Is there such a module? If not, is it needed? Or is there a simpler approach which I've overlooked?

Crosspost: stackoverflow


In reply to Module for executing postponed initialization code by Dallaylaen

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.