Data::...Object(3pm)
okay so this is Data::ObjectDriver::BaseObject(3pm) from the User Contributed Perl Documentation, and it's literally the base class for modeled objects. No cap, this page is the whole blueprint for getting your data objects to behave, bestie π
π NAME π
Data::ObjectDriver::BaseObject β base class for modeled objects π«Ά
β¨ SYNOPSIS β¨
bestie, here's the whole setup in one look:
package Ingredient;
use base qw( Data::ObjectDriver::BaseObject );
__PACKAGE__->install_properties({
columns => [ 'ingredient_id', 'recipe_id', 'name', 'quantity' ],
datasource => 'ingredient',
primary_key => [ 'recipe_id', 'ingredient_id' ],
driver => FoodDriver->driver,
});
__PACKAGE__->has_a(
{ class => 'Recipe', column => 'recipe_id', }
);
package main;
my ($ingredient) = Ingredient->search({ recipe_id => 4, name => 'rutabaga' });
$ingredient->quantity(7);
$ingredient->save();
π DESCRIPTION π
Data::ObjectDriver::BaseObject provides services to data objects modeled with the Data::ObjectDriver object relational mapper. That's the whole point, and it's iconic β¨
πΈ CLASS DEFINITION πΈ
This is where you define the class's whole personality β its columns, datasource, driver, all of it π
π
Class->install_properties(\%params) π
Defines all the properties of the specified object class. Generally you should call install_properties() in the body of your class definition, so the properties can be set when the class is used or required.
Required members of %params are:
columnsβ All the columns in the object class. This property is an arrayref.datasourceβ The identifier of the table in which the object class's data are stored. Usually the datasource is simply the table name, but the datasource can be decorated into the table name by theData::ObjectDriver::DBDmodule if the database requires special formatting of table names.driverorget_driverβ The driver used to perform database operations (lookup, update, etc) for the object class.
driver is the instance of Data::ObjectDriver to use. If your driver requires configuration options not available when the properties are initially set, specify a coderef as get_driver instead. It will be called the first time the driver is needed, storing the driver in the class's driver property for subsequent calls.
The optional members of %params are:
primary_keyβ The column or columns used to uniquely identify an instance of the object class. If one column (such as a simple numeric ID) identifies the class,primary_keyshould be a scalar. Otherwise,primary_keyis an arrayref.column_defsβ Specifies types for specially typed columns, if any, as a hashref. For example, if a column holds a timestamp, name it incolumn_defsas adatefor proper handling with someData::ObjectDriver::Driver::DBDdatabase drivers. Columns for which types aren't specified are handled ascharcolumns.
Known column_defs types are:
blobβ A blob of binary data.Data::ObjectDriver::Driver::DBD::Pgmaps this toDBI::Pg::PG_BYTEA,DBD::SQLitetoDBI::SQL_BLOBandDBD::OracletoORA_BLOB.bin_charβ A non-blob string of binary data.Data::ObjectDriver::Driver::DBD::SQLitemaps this toDBI::SQL_BINARY.
Other types may be defined by custom database drivers as needed, so consult their documentation.
dbβ The name of the database. When used withData::ObjectDriver::Driver::DBItype object drivers, this name is passed to theinit_dbmethod when the actual database handle is being created.
Custom object drivers may define other properties for your object classes. Consult the documentation of those object drivers for more information.
π οΈ Class->install_column($col, $def) π οΈ
Modify the Class definition to declare a new column $col of definition <$def> (see column_defs). Lowkey handy for adding a column without rewriting the whole property block π«Ά
πΌ Class->has_a(@definitions) πΌ
β οΈ NOTE: has_a is an experimental system, likely to both be buggy and change in future versions.
Defines a foreign key reference between two classes, creating accessor methods to retrieve objects both ways across the reference. For each defined reference, two methods are created: one for objects of class Class to load the objects they reference, and one for objects of the referenced class to load the set of Class objects that reference them.
For example, this definition:
package Ingredient;
__PACKAGE__->has_a(
{ class => 'Recipe', column => 'recipe_id' },
);
would create Ingredient->recipe_obj and Recipe->ingredient_objs instance methods.
Each member of @definitions is a hashref containing the parameters for creating one accessor method. The required members of these hashes are:
classβ The class to associate.columnβ The column or columns in this class that identify the primary key of the associated object. As with primary keys, use a single scalar string for a single column or an arrayref for a composite key.
The optional members of has_a() definitions are:
methodβ The name of the accessor method to create.
By default, the method name is the concatenated set of column names with each _id suffix removed, and the suffix _obj appended at the end of the method name. For example, if column were ['recipe_id', 'ingredient_id'], the resulting method would be called recipe_ingredient_obj by default.
cachedβ Whether to keep a reference to the foreign object once it's loaded. Subsequent calls to the accessor method would return that reference immediately.parent_methodβ The name of the reciprocal method created in the referenced class named inclass.
By default, that method is named with the lowercased name of the current class with the suffix _objs. For example, if in your Ingredient class you defined a relationship with Recipe on the column recipe_id, this would create a $recipe->ingredient_objs method.
Note that if you reference one class with multiple sets of fields, you can omit only one parent_method; otherwise the methods would be named the same thing. For instance, if you had a Friend class with two references to User objects in its user_id and friend_id columns, one of them would need a parent_method.
π¦ Class->has_partitions(%param) π¦
Defines that the given class is partitioned, configuring it for use with the Data::ObjectDriver::Driver::SimplePartition object driver. Required members of %param are:
numberβ The number of partitions in which objects of this class may be stored.get_driverβ A function that returns an object driver, given a partition ID and any extra parameters specified when the class'sData::ObjectDriver::Driver::SimplePartitionwas instantiated.
Note that only the parent object for use with the SimplePartition driver should use has_partitions(). See Data::ObjectDriver::Driver::SimplePartition for more about partitioning.
π₯ BASIC USAGE π₯
okay bestie, now the actual day-to-day moves:
π Class->lookup($id) π
Returns the instance of Class with the given value for its primary key. If Class has a complex primary key (more than one column), $id should be an arrayref specifying the column values in the same order as specified in the primary_key property.
β Class->search(\%terms, [\%args]) β
Returns all instances of Class that match the values specified in \%terms, keyed on column names. In list context, search returns the objects containing those values. In scalar context, search returns an iterator function containing the same set of objects.
Your search can be customized with parameters specified in \%args. Commonly recognized parameters (those implemented by the standard Data::ObjectDriver object drivers) are:
sortβ A column by which to order the object results.directionβ If set todescend, the results (ordered by thesortcolumn) are returned in descending order. Otherwise, results will be in ascending order.limitβ The number of results to return, at most. You can use this withoffsetto paginate yoursearch()results.offsetβ The number of results to skip before the first returned result. Use this withlimitto paginate yoursearch()results.fetchonlyβ A list (arrayref) of columns that should be requested. If specified, only the specified columns of the resulting objects are guaranteed to be set to the correct values.
Note that any caching object drivers you use may opt to ignore fetchonly instructions, or decline to cache objects queried with fetchonly.
for_updateβ If true, instructs the object driver to indicate the query is a search, but the application may want to update the data after. That is, the generated SQLSELECTquery will include aFOR UPDATEclause.
All options are passed to the object driver, so your driver may support additional options.
π Class->result(\%terms, [\%args]) π
Takes the same %terms and %args arguments that search takes, but instead of executing the query immediately, returns a Data::ObjectDriver::ResultSet object representing the set of results. It's giving "search, but make it a whole object" β¨
π $obj->exists() π
Returns true if $obj already exists in the database.
π $obj->save() π
Saves $obj to the database, whether it is already there or not. That is, save() is functionally:
$obj->exists() ? $obj->update() : $obj->insert()
π $obj->update() π
Saves changes to $obj, an object that already exists in its database.
π§ $obj->insert() π§
Adds $obj to the database in which it should exist, according to its object driver and configuration.
π $obj->remove() π
Deletes $obj from its database.
π $obj->replace() π
Replaces $obj in the database. Does the right thing if the driver knows how to REPLACE object, ala MySQL.
part 2 is literally right there, bestie β keep reading β¨
π» USAGE π»
Okay bestie, this is where the object actually starts doing stuff. Every method here is a little tool in the kit β grab the one you need, don't skip any, because they all matter. π
Class->new(%columns)β Returns a brand-new object of the given class, with its columns initialized using the values in%columns.$obj->init(%columns)β Initializes$objiby initializing its columns with the values in%columns.
Override this method if you need to do initial configuration for new instances of $obj's class, and that setup is not better off as a post_load callback.
Class->properties()β Returns the named object class's properties as a hashref. Quick note: some standard object class properties, likeprimary_key, have more convenient accessors than reading the properties hash directly.Class->driver()β Returns the object driver for this class. If it needs to, it invokes the class'sget_driverfunction and caches the result for future calls.Class->get_driver($get_driver_fn)β Sets the function used to find the object driver forClassobjects β that is, theget_driverproperty.
Heads up: once driver() has been called, the get_driver function is not used. Usually you'd specify your function as the get_driver parameter to install_properties().
Class->is_pkless()β Returns whether the given object class has a primary key defined.Class->is_primary_key($column)β Returns whether the given column is, or is part of, the primary key forClassobjects.$obj->primary_key()β Returns the values of the primary key fields of$obj.Class->primary_key_tuple()β Returns the names of the primary key fields ofClassobjects.$obj->is_same($other_obj)β Does a primary key check on$objand$<other_obj>, and returns true only if they're identical.$obj->object_is_stored()β Returns true if the object hasn't been stored in the database yet. This is especially useful in triggers, where it helps you figure out if the object is beingINSERTEDor justUPDATED.$obj->pk_str()β Returns the primary key as a printable string.$obj->has_primary_key()β Returns whether the given object has values for all of its primary key fields.$obj->uncache_object()β If you use a Cache driver, returned objects get automatically cached as a result of common retrieve operations. In some rare cases you may want the cache cleared explicitly, and this method gives you a way to do that.$obj->primary_key_to_terms([$id])β Returns$obj's primary key as a hashref of values keyed on column names, suitable for passing assearch()terms. If$idis specified, convert that primary key instead of$obj's.Class->datasource()β Returns the datasource for objects of classClass. That is, it returns thedatasourceproperty ofClass.Class->columns_of_type($type)β Returns the list of columns inClassobjects that hold data of type$type, as an arrayref. Columns count as a certain type when they're set that way inClass'scolumn_defsproperty.$obj->set_values(\%values)β Sets all the columns of$objthat are members of\%valuesto the values specified there.$obj->set_values_internal(\%values)β Sets the new specified values of$objwithout using any overridden mutator methods of$obj, and without marking the changed columns as changed.$obj->clone()β Returns a new object of the same class as$objcontaining the same data, except for primary keys, which are set toundef.$obj->clone_all()β Returns a new object of the same class as$objcontaining the same data, including all key fields.Class->has_column($column)β Returns whether a column named$columnexists in objects of classClass.Class->column_names()β Returns the list of columns inClassobjects as an arrayref.$obj->column_values()β Returns the columns and values in the given object as a hashref.$obj->column($column, [$value])β Returns the value of$obj's column$column. If$valueis specified,column()sets it first.
Note that the usual way to access and mutate column values is through the named accessors:
$obj->column('fred', 'barney'); # possible
$obj->fred('barney'); # preferred
$obj->is_changed([$column])β Returns whether any values in$objhave changed. If$columnis given, returns specifically whether that column has changed.$obj->changed_cols_and_pk()β Returns the list of all columns that have changed in$objsince it was last loaded from or saved to the database, as a list.$obj->changed_cols()β Returns the list of changed columns in$objas a list, except for any columns in$obj's primary key β even if they have changed.Class->lookup_multi(\@ids)β Returns a list (arrayref) of objects as specified by their primary keys.Class->bulk_insert(\@columns, \@data)β Adds the given data β an arrayref of arrayrefs containing column values in the order of the column names given in\@columnsβ directly to the database asClassrecords.
Note that only some database drivers implement the bulk insert operation β for example, Data::ObjectDriver::Driver::DBD::Pg.
$obj->fetch_data()β Returns the current values from$objas saved in the database, as a hashref.$obj->refresh()β Resets the values of$objfrom the database. Any unsaved modifications to$objwill be lost, and any made meanwhile will be reflected in$objafterward.$obj->column_func($column)β Creates an accessor/mutator method for column$column, returning it as a coderef.
Override this if you need special behavior in all accessor/mutator methods.
$obj->deflate()β Returns a minimal representation of the object, for use in caches where you might want to preserve space (like memcached). Subclasses can also override this to store the optimal representation of an object in the cache. For example, if you have metadata attached to an object, you might want to store that in the cache too.Class->inflate($deflated)β Inflates the deflated representation of the object$deflatedinto a proper object in the classClass. That is, it undoes the operation$deflated = $obj->deflate()by returning a new object equivalent to$obj.
π TRANSACTION SUPPORT AND METHODS π
π± Introduction π±
When you're dealing with the methods on this class, the transactions are global β meaning they're applied to all drivers. You can still enable transactions per driver if you directly use the driver API. Slay, but be aware. π
Class->begin_workβ Enables transactions globally for all drivers until the nextrollbackorcommitcall on the class.
If begin_work is called while a transaction is still active (a nested transaction), then the two transactions are merged. So inner transactions are ignored, and a warning will be emitted. Not me ignoring the inner transaction π.
Class->rollbackβ Rolls back all the transactions since the last begin work, and exits from the active transaction state.Class->commitβ Commits the transactions, and exits from the active transaction state.Class->txn_debugβ Just returns the value of the global flag and the current working drivers in a hashref.Class->txn_activeβ Returns true if a transaction is already active.
π©Ί DIAGNOSTICS π©Ί
These are the "bestie, what happened" messages. Read them like your code is texting you for help. π
"Please specify a valid column for class"β One of the class relationships you defined withhas_a()was missing acolumnmember."Please define a valid method for column"β One of the class relationships you defined withhas_a()was missing itsmethodmember and a method name could not be generated, or the class for which you specified the relationship already has a method by that name. Perhaps you specified an additional accessor by the same name for that class."keys don't match with primary keys: list"β The hashref of values you passed as the ID toprimary_key_to_terms()was missing members or had extra members. Perhaps you used a fullcolumn_values()hash instead of only including that class's key fields."You tried to set inexistent column column name to value data on class name"β The hashref you specified toset_values()contained keys that are not defined columns for that class of object. Perhaps you invoked it on the wrong class, or did not fully filter members of the hash out before using it."Cannot find column 'column' for class 'class'"β The column you specified tocolumn()does not exist for that class, you attempted to use an automatically generated accessor/mutator for a column that doesn't exist, or you attempted to use a column accessor as a class method instead of an instance method. Perhaps you performed your call on the wrong class or variable, or misspelled a method or column name."Must specify column"β You invoked thecolumn_func()method without specifying a column name. Column names are required to create the accessor/mutator function, so it knows what data member of the object to use."number (of partitions) is required"β You attempted to define partitioning for a class without specifying the number of partitions for that class in thenumbermember. Perhaps your logic for determining the number of partitions resulted inundefor0."get_driver is required"β You attempted to define partitioning for a class without specifying the function to find the object driver for a partition ID as theget_drivermember.
π BUGS AND LIMITATIONS π
There are no known bugs in this module. Iconic behavior, honestly. β¨
π SEE ALSO π
Go touch grass in these other modules, bestie:
Data::ObjectDriverData::ObjectDriver::Driver::DBIData::ObjectDriver::Driver::SimplePartition
π LICENSE π
Data::ObjectDriver is free software; you may redistribute it and/or modify it under the same terms as Perl itself.
π AUTHOR & COPYRIGHT π
Except where otherwise noted, Data::ObjectDriver is Copyright 2005-2006 Six Apart, cpan@sixapart.com. All rights reserved.
That's the whole vibe, bestie π β this page came from perl v5.42.0, dated 2024-10-24, and those footer details are getting their cute little shoutout right here instead of being pasted as a line. π
π¦ where this page comes from
- opensuse-leap 16.0: perl-Data-ObjectDriver 0.230.0-bp160.1.12 Β· Artistic-1.0 OR GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms