packetstormer has asked for the wisdom of the Perl Monks concerning the following question:
Hi Monks
EDIT: Changed Package name from DB to MyDB to avoid conflicts - same query applies
I am struggling (still) with the practical use of OOP. I have written quite a lot of procedural code but I would like to start moving into OOP some more. My main question is less to do with code and more to do with logic!
A simple example is using OOP with a database.
Suppose I create a simple class called DB and within it a method called 'new' and a method called 'get_sites' as:
package MyDB; use strict; use DBI; use Config::Tiny; use Data::Dumper; sub new { my $class = shift; my $self = {}; my $file = shift || 'config.cfg'; my $cnf = Config::Tiny->read($file); my $dbh = DBI->connect("DBI:mysql:dbname=$cnf->{database}->{DATABA +SE};host=$cnf->{database}->{IP};port=$cnf->{database}->{PORT}", $cnf->{database}->{USER}, $cnf->{database}- +>{PASS}, {RaiseError=>1, mysql_enable_utf8 => 1}); $self->{dbh} = $dbh; bless $self,$class; return $self; } sub get_sites { my $self = shift; my $sth = $self->{dbh}->prepare("SELECT * from sites"); $sth->execute(); $self->{sites} = $sth->fetchall_arrayref({}); } 1;
Firstly, is it wise to place the database handle in the instance?.
Secondly, all the example I see manipulate (add, remove)to $self. However, I am unsure why this is needed. Take the above example, if I do:
I get the output of the sites table into my instance. However, I am not sure what I would want to use that again in this instance. So, if I called another method called, say, add_site, the $self->{sites} is still there, needlessly. I feel that logically, I should called DB->new() ahead of every other call i.e before I call delete_site or add_user because I can't see anything common between the methods!#!/usr/bin/perl use strict; use MyDB; use Data::Dumper; my $dbh = MyDB->new('config.cfg'); my $test = $dbh->get_sites(); print Dumper $test;
I realise I am not explaining this too well but I am sort of wondering if there is even a need for OOP in this type of setup. I am having trouble understanding the beneifit. I have read "Object Orinented Perl" and I am still unsure how I would apply it to an easy web applicaiton
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: OOP Confusion
by CountZero (Bishop) on Mar 21, 2014 at 17:28 UTC | |
by locked_user sundialsvc4 (Abbot) on Mar 21, 2014 at 19:06 UTC | |
by CountZero (Bishop) on Mar 21, 2014 at 19:58 UTC | |
|
Re: OOP Confusion
by locked_user sundialsvc4 (Abbot) on Mar 21, 2014 at 13:59 UTC | |
|
Re: OOP Confusion (package DB;)
by Anonymous Monk on Mar 21, 2014 at 13:07 UTC | |
|
Re: OOP Confusion
by Bloodnok (Vicar) on Mar 22, 2014 at 12:07 UTC |