Why do we use the Catalyst context object? What is his purpose?

I thought I really did not understand why almost everyone in the catalysis uses a context object. Almost everything seems to start with

my ( $self, $c ) = @_;

we transfer the DBIC with the catalyst model and finish

$c->model('DBIC::Table') ...

or maybe we do

$c->log->warn('foo');

but I don’t understand why we just don’t

log('warn', 'foo'); # or whatever the API for some log library is.

Why do we do everything except the context object? what makes it special?

+5
source share
3 answers

, ( , ), . , , , . , ( IoC) .

, , . , .. , .

+5

Perl "", . , , . ( ).

, , , Javascript with. Perl , , :

use warnings;
use strict;
use Carp ();

sub with ($&) {
    my ($obj, $code) = @_;
    my $auto = (caller).'::AUTOLOAD';
    no strict 'refs';
    local *$auto = sub {
        my ($name) = $$auto =~ /([^:]+)$/;
        my $method = $obj->can($name)
                  || $obj->can(lcfirst $name)
            or Carp::croak "no method '$name' on '$obj' in with block";
        unshift @_, $obj;
        goto &$method
    };
    $code->()
}

:

{package Obj;
    sub new   {bless []}
    sub log   {shift; say "logging @_"}
    sub model {shift; say "setting model to @_"}
}

:

my $c = Obj->new;

with $c => sub {
    model('DBIC::Table');
    Log('hello world');   # ucfirst
    &log('hello again');  # or with a & since 'log' is a builtin
};

:

setting model to DBIC::Table
logging hello world
logging hello again

, , with. ucfirst . with parens Log('hello'), Log 'hello', .

+2

- , Catalyst:: Controller. , Catalyst Controller URL-. , , Catalyst log, URL?

sub log : Local { ... }. , , . , .

, Perl . $/, $_, $] .. , $INPUT_RECORD_SEPARATOR $RS , , , , , .

, , $c, . , $c->log->disable('warn', 'error') . . , .

, , , . , ( $c ) , .

, $c. , Log:: Log4Perl , $c->log . . , - , .

And at least there is no rule that you should use $c. For example, I myself use DateTime directly and create new objects and do not use Catalyst :: Plugin :: DateTime, which allows me to do this $c->datetime. And I do not see any benefit from the latter. Just because there are many extension plugins $cdoes not mean that they are useful or you should use them.

+1
source

All Articles