Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

Perl Singleton Objects

This is a quick introduction to perl Singleton objects. A singleton object is an object that is only instantiated once throughout an application.

Singleton Uses

Singletons can be used for many things. If you only want one database connection for a particular application, or a limited number of connections a singleton database class can handle managing your open connections.

How to implement

The following is an example of how to put together a database object that opens a database connection and returns an existing connection to the caller.This allows your userid/password to be set in a single location as well. You don't have to have every piece of code that accesses the database use userid/password. Just use the DBConnector object and then issue your database calls.
package DBconnector; my $singleton; sub new { my $class = shift; $singleton ||= bless {}, $class; } sub connect { my $self = shift; if (exists $self->{dbh}) { $self->{dbh}; } else { my $connection = "dbi:mysql:host=$self->{host} \ dbname=$self->{name}"; $self->{dbh} = DBI->connect($connection, \ $self->{user},$self->{password}); } }

Summary

There are many ways to use singletons. This is just a basic example, but provides what is needed to create a singleton object.

In reply to Perl Singletons by sheridan3003

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



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (4)
As of 2024-04-19 17:53 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found