?? object.pm
字號:
I<@objects> will be returned; this works well when you know that your I<load>call can only ever result in one object returned--for example, when you loadan object by ID.I<\%terms> should be either:=over 4=item *The numeric ID of an object in the datastore.=item *A reference to a hash where the keys are column names and the values arethe values for that column. For example, to load an I<MT::Foo> object wherethe I<foo> column is equal to C<bar>, you could do this: my @foo = MT::Foo->load({ foo => 'bar' });In addition to a simple scalar, the hash value can be a reference to an array;combined with the I<range> setting in the I<\%arguments> list, you can usethis to perform range searches. If the value is a reference, the first elementin the array specifies the low end of the range, and the second element thehigh end.=backI<\%arguments> should be a reference to a hash containing parameters for thesearch. The following parameters are allowed:=over 4=item * sort => "column"Sort the resulting objects by the column C<column>; C<column> must be anindexed column (see L<indexes>, above).=item * direction => "ascend|descend"To be used together with I<sort>; specifies the sort order (ascending ordescending). The default is C<ascend>.=item * limit => "N"Rather than loading all of the matching objects (the default), load onlyC<N> objects.=item * offset => "M"To be used together with I<limit>; rather than returning the first C<N>matches (the default), return matches C<M> through C<N + M>.=item * start_val => "value"To be used together with I<limit> and I<sort>; rather than returning thefirst C<N> matches, return the first C<N> matches where C<column> (the sortcolumn) is greater than C<value>.=item * rangeTo be used together with an array reference as the value for a column inI<\%terms>; specifies that the specific column should be searched for a rangeof values, rather than one specific value.The value of I<range> should be a hash reference, where the keys are columnnames, and the values are all C<1>; each key specifies a column that shouldbe interpreted as a range.=item * joinCan be used to select a set of objects based on criteria, or sorted bycriteria, from another set of objects. An example is selecting the C<N>entries most recently commented-upon; the sorting is based on I<MT::Comment>objects, but the objects returned are actually I<MT::Entry> objects. UsingI<join> in this situation is faster than loading the most recentI<MT::Comment> objects, then loading each of the I<MT::Entry> objectsindividually.Note that I<join> is not a normal SQL join, in that the objects returned arealways of only one type--in the above example, the objects returned are onlyI<MT::Entry> objects, and cannot include columns from I<MT::Comment> objects.I<join> has the following general syntax: join => [ CLASS, JOIN_COLUMN, I<\%terms>, I<\%arguments> ]I<CLASS> is the class with which you are performing the join; I<JOIN_COLUMN>is the column joining the two object tables. I<\%terms> and I<\%arguments>have the same meaning as they do in the outer I<load> or I<load_iter>argument lists: they are used to select the objects with which the join isperformed.For example, to select the last 10 most recently commmented-upon entries, youcould use the following statement: my @entries = MT::Entry->load(undef, { 'join' => [ 'MT::Comment', 'entry_id', { blog_id => $blog_id }, { 'sort' => 'created_on', direction => 'descend', unique => 1, limit => 10 } ] });In this statement, the I<unique> setting ensures that the I<MT::Entry>objects returned are unique; if this flag were not given, two copies of thesame I<MT::Entry> could be returned, if two comments were made on the sameentry.=item * uniqueEnsures that the objects being returned are unique.This is really only useful when used within a I<join>, because when loadingdata out of a single object datastore, the objects are always going to beunique.=back=head2 Removing an objectTo remove an object from the datastore, call the I<remove> method on anobject that you have already loaded using I<load>: $foo->remove;On success, I<remove> will return some true value; on failure, it will returnC<undef>, and you can retrieve the error message by calling the I<errstr>method on the object: $foo->remove or die "Removing foo failed: ", $foo->errstr;If you are removing objects in a loop, take a look at the L<Note on ObjectLocking>.=head2 Removing all of the objects of a particular classTo quickly remove all of the objects of a particular class, call theI<remove_all> method on the class name in question: MT::Foo->remove_all;On success, I<remove_all> will return some true value; on failure, it willreturn C<undef>, and you can retrieve the error message by calling theI<errstr> method on the class name: MT::Foo->remove_all or die "Removing all foo objects failed: ", MT::Foo->errstr;=head2 Getting the count of a number of objectsTo determine how many objects meeting a particular set of conditions exist,use the I<count> method: my $count = MT::Foo->count({ foo => 'bar' });I<count> takes the same arguments (I<\%terms> and I<\%arguments>) as I<load>and I<load_iter>, above.=head2 Determining if an object exists in the datastoreTo check an object for existence in the datastore, use the I<exists> method: if ($foo->exists) { print "Foo $foo already exists!"; }=head2 Counting groups of objectsThe count_group_by method can be used (with SQL-based ObjectDrivers)to retrieve a list of all the distinct values that appear in a givencolumn along with a count of how many objects carry that value. Theroutine can also be used with more than one column, in which case itretrieves the distinct pairs (or n-tuples) of values in those columns,along with the counts. Yet more powerful, any SQL expression can beused in place of the column names to count how many object produce anygiven result values when run through those expressions. $iter = MT::Foo->count_group_by($terms, {%args, group => $group_exprs});C<$terms> and C<%args> pick out a subset of the MT::Foo objects in theusual way. C<$group_expressions> is an array reference containing theSQL expressions for the values you want to group by. A single row willbe returned for each distinct tuple of values resulting from the$group_expressions. For example, if $group_expressions were just asingle column (e.g. group => ['created_on']) then a single row wouldbe returned for each distinct value of the 'created_on' column. If$group_expressions were multiple columns, a row would be returned foreach distinct pair (or n-tuple) of values found in those columns.Each application of the iterator C<$iter> returns a list in the form: ($count, $group_val1, $group_val2, ...)Where C<$count> is the number of MT::Foo objects for which the groupexpressions are the values ($group_val1, $group_val2, ...). Thesevalues are in the same order as the corresponding group expressions inthe $group_exprs argument.In this example, we load up groups of MT::Pip objects, grouped by thepair (cat_id, invoice_id), and print how many pips have that pair ofvalues. $iter = MT::Pip->count_group_by(undef, {group => ['cat_id', 'invoice_id']}); while (($count, $cat, $inv) = $iter->()) { print "There are $count Pips with " . "category $cat and invoice $inv\n"; }=head2 Inspecting and Manipulating Object StateUse C<column_values> and C<set_values> to get and set the fields of anobject I<en masse>. The former returns a hash reference mapping columnnames to their values in this object. For example: $values = $obj->column_values()C<set_values> accepts a similar hash ref, which need not give a valuefor every field. For example: $obj->set_values({col1 => $val1, col2 => $val2});is equivalent to $obj->col1($val1); $obj->col2($val2);=head2 Other Methods=over 4=item * $obj->clone()Returns a clone of C$<obj>--that is, a distinct object which has allthe same data stored within it. Changing values within one object doesnot modify the other.=item * $obj->column_names()Returns a list of the names of columns in C<$obj>; includes all thosespecified to the install_properties method as well as the auditproperties (C<created_on>, C<modified_on>, C<created_by>,C<modified_by>), if those were enabled in install_properties.=item * MT::Foo->driver()=item * $obj->driver()Returns the ObjectDriver object that links this object with a database.=item * $obj->created_on_obj()Returns an MT::DateTime object representing the moment when theobject was first saved to the database.=item * MT::Foo->set_by_key($key_terms, $value_terms)A convenience method that loads whatever object matches the C<$key_terms>argument and sets some or all of its fields according to theC<$value_terms>. For example: MT::Foo->set_by_key({name => 'Thor'}, {region => 'Norway', gender => 'Male'});This loads the C<MT::Foo> object having 'name' field equal to 'Thor'and sets the 'region' and 'gender' fields appropriately.More than one term is acceptable in the C<$key_terms> argument. Thematching object is the one that matches all of the C<$key_terms>.This method only useful if you know that there is a unique objectmatching the given key. There need not be a unique constraint on thecolumns named in the C<$key_hash>; but if not, you should be confidentthat only one object will match the key.=back=head1 NOTES=head2 Note on object lockingWhen you read objects from the datastore, the object table is locked with ashared lock; when you write to the datastore, the table is locked with anexclusive lock.Thus, note that saving or removing objects in the same loop where you areloading them from an iterator will not work--the reason is that the datastoremaintains a shared lock on the object table while objects are being loadedfrom the iterator, and thus the attempt to gain an exclusive lock when savingor removing an object will cause deadlock.For example, you cannot do the following: my $iter = MT::Foo->load_iter({ foo => 'bar' }); while (my $foo = $iter->()) { $foo->remove; }Instead you should do either this: my @foo = MT::Foo->load({ foo => 'bar' }); for my $foo (@foo) { $foo->remove; }or this: my $iter = MT::Foo->load_iter({ foo => 'bar' }); my @to_remove; while (my $foo = $iter->()) { push @to_remove, $foo if SOME CONDITION; } for my $foo (@to_remove) { $foo->remove; }This last example is useful if you will not be removing every I<MT::Foo>object where I<foo> equals C<bar>, because it saves memory--only theI<MT::Foo> objects that you will be deleting are kept in memory at the sametime.=head1 CALLBACKSMost MT::Object operations can trigger callbacks to plugin code. Somenotable uses of this feature are: to be notified when a database record ismodified, or to pre- or post-process the data being flowing to thedatabase.To add a callback, invoke the C<add_callback> method of the I<MT::Object>subclass, as follows: MT::Foo->add_callback("pre_save", <priority>, <plugin object>, \&callback_function);The first argument is the name of the hook point. Any I<MT::Object>subclass has a pre_ and a post_ hook point for each of the followingoperations: load save remove remove_all (load_iter operations will call the load callbacks)The second argument, E<lt>priorityE<gt>, is the relative order inwhich the callback should be called. The value should be between 1 and10, inclusive. Callbacks with priority 1 will be called before thosewith 2, 2 before 3, and so on.Plugins which know they need to run first or last can use the priorityvalues 0 and 11. A callback with priority 0 will run before allothers, and if two callbacks try to use that value, an error willresult. Likewise priority 11 is exclusive, and runs last.How to remember which callback priorities are special? As you know,most guitar amps have a volume knob that goes from 1 to 10. But, likethat of certain rock stars, our amp goes up to 11. A callback withpriority 11 is the "loudest" or most powerful callback, as it will becalled just before the object is saved to the database (in the case ofa 'pre' callback), or just before the object is returned (in the caseof a 'post' callback). A callback with priority 0 is the "quietest"callback, as following callbacks can completely overwhelm it. This maybe a good choice for your plugin, as you may want your plugin to workwell with other plugins. Determining the correct priority is a matterof thinking about your plugin in relation to others, and adjusting thepriority based on experience so that users get the best use out of theplugin.The E<lt>plugin objectE<gt> is an object of type MT::Plugin whichgives some information about the plugin. This is used to includethe plugin's name in any error messages.E<lt>callback functionE<gt> is a code referense for a subroutine thatwill be called. The arguments to thisfunction vary by operation (see I<MT::Callback> for details),but in each case the first parameter is the I<MT::Callback> objectitself: sub my_callback { my ($cb, ...) = @_; if ( <error condition> ) { return $cb->error("Error message"); } }Strictly speaking, the return value of a callback is ignored. Callingthe error() method of the MT::Callback object (C<$cb> in this case)propagates the error message up to the MT activity log. Another way to handle errors is to call C<die>. If a callback dies,I<MT> will warn the error to the activity log, but will continueprocessing the MT::Object operation: so other callbacks will stillrun, and the database operation should still occur.=head2 CaveatBe careful how you handle errors. If you transform data as it goesinto and out of the database, and it is possible for one of yourcallbacks to fail, the data may get saved in an undefined state. Itmay then be difficult or impossible for the user to recover that data.=head1 AUTHOR & COPYRIGHTSPlease see the I<MT> manpage for author, copyright, and license information.=cut
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -