install OPsudo perl -MCPAN -e 'install OP' This installs the latest stable version of OP. You will also need DBD::mysql. create a databaseOP will create any necessary tables, but a DBA must create the initial database, as well as run any required GRANT statements. mysql -u root -p create database yourapp; grant all on yourapp.* to op@localhost; create an object classIn file YourApp/Example.pm:
use strict;
use warnings;
use OP;
create "YourApp::Example" => { };
assert variable typesAsserted types map to same-named database table columns.
create "YourApp::Example" => {
favoriteNumber => OP::Int->assert(
::optional
),
favoriteColor => OP::Str->assert(
qw| red green blue |,
::optional
),
};
By default, instances will already have: id, name, ctime, and mtime. |
make a new objectuse YourApp::Example; my $class = "YourApp::Example"; my $example = $class->new( name => "HelloWorld" ); save an object$example->save; load an objectLoad by GUID: my $example = $class->load($id); Load by Name:
my $example = $class->loadByName("HelloWorld");
remove an object$example->remove query the databaseUse DBI statement handles:
my $sth = $class->query(
sprintf q| select id, name from %s |,
$class->tableName
);
while ( my @row = $sth->fetchrow_array ) {
print join ",", @row;
print "\n";
};
|
set, get, and delete an attributeExplicit:
$example->setFavoriteColor("blue");
my $color = $example->favoriteColor;
$example->deleteFavoriteColor;
Iterative:
$example->set("favoriteColor", "blue");
my $color = $example->get("favoriteColor");
$example->delete("favoriteColor");
dump object to json or yamlmy $json = $object->toJson; my $yaml = $object->toYaml; # # Prints YAML # $object->print; load json or yaml as objectmy $examp1 = $class->loadJson($json); my $examp2 = $class->loadYaml($yaml); assert a foreign id constraintUse OP::ExtID:
create "YourApp::ThisClass" => {
relatedId => OP::ExtID->assert(
"YourApp::OtherClass"
),
};
|
class methodInline:
create "YourApp::Example" => {
someMethod => sub {
my $class = shift;
# ...
},
};
instance methodInline:
create "YourApp::Example" => {
someMethod => sub {
my $self = shift;
# ...
},
};
|
OP classes may be instantiated ($class->new(...)), or declared as inline attributes ($class->assert(...)). collect array elements
my $collected = $array->collect( sub {
my $item = shift;
print "Working with element $item\n"
return if $item == $foo; # Yield nothing
break if $item == $bar; # Stop collecting
# Upstream $things, continue curr iteration:
emit $thing1, [$thing2, ...];
# Upstream $things, skip to next iteration:
yield $thing1, [$thing2, ...];
} );
|