1. Perl
  2. Module
  3. here

Object::Simple - Generate Mojo::Base compatible accessor

Use Object::Simple to create an accessor with a default value. Object::Simple is highly compatible with Mojolicious's Mojo::Base.

package Point;
use Object::Simple -base;

has x => 1;
has y => 1;

package main;

my $point = Point->new;
print $point->x;

1;

You can inherit Object::Simple by specifying -base when using. Object::Simple has a new method. It also imports a method called has for defining accessors. Also, strict and warnings are automatically enabled.

General class example

This is an example of a general class. The Point class has accessors x and y. It also has a method called clear that initializes x and y to 0.

package Point;
use Object::Simple -base;

has x => 0;
has y => 0;

sub clear {
  my $self = shift;
    
  $self->x(0);
  $self->y(0);
}

1;

Use the Point class as follows: The constructor new is inherited from Object::Simple.

my $point = Point->new(x => 4, y => 6);

$point->x(1);
$point->y(2);

my $x = $point->x;
my $y = $point->y;

$point->clear;

How to use Object::Simple

There are several ways to define attributes.

Define multiple attributes at once

# No default value
has ['x', 'y'];

# With default value
has ['x', 'y'] => 0;

You can define multiple accessors at once by specifying the array reference as the first argument of has.

Specify default value

# Constant
has foo => 1;

# Array reference
has foo => sub {[]};

# Hash reference
has bar => sub {{}};

# object
has baz => sub {LWP::UserAgent->new};

When setting array reference, hash reference, objects, etc. to default values, you need to enclose them in sub {} for lazy evaluation.

Define all accessors at once

has [qw/foo bar baz /],
    some => 1,
    other => sub {5};

You can also define all accessors at once.

Inheritance example

This is an example to create a Point3D class that inherits the Point class.

package Point3D;
use Point -base;

has z => 0;

sub clear {
  my $self = shift;
  $self->SUPER::clear ();
  $self->z(0);
}

1;

Constructor override

You can override the constructor new() for object initialization and argument processing.

# Override new() for object initialization
sub new {
  my $self = shift->SUPER::new(@_);
  
  # Initialization
  
  return $self;
}
# Override new() for argument processing
sub new {
  my $self = shift;
  
  $self->SUPER::new(x => $_[0], y => $_[1]);
  
  return $self;
}

Related Informatrion