Модераторы: korob2001, ginnie
  

Поиск:

Ответ в темуСоздание новой темы Создание опроса
> Catalyst Model to Model 
:(
    Опции темы
gcc
Дата 6.10.2009, 05:26 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Агент алкомафии
****


Профиль
Группа: Участник
Сообщений: 2691
Регистрация: 25.4.2008
Где: %&й

Репутация: 2
Всего: 17



понадобилось вызвать в одной моей модели еще одну модель DBI my $dbh = $c->model('DBI')->dbh;
MVC архитектура это позволяет

есть код, где наследуется конструктор и есть $c, я думал что все будет в порядке

Код

package MyApp::Model::Tree;

 use strict;
use warnings;

use parent 'Catalyst::Model';

use Class::C3::Adopt::NEXT;
use DBIx::Tree;


sub new {
    my ( $self, $c ) = @_;

    $self = $self->next::method(@_);

        my $sql = "SELECT id_se, name_se, parent_se_id
                       FROM section ";    
        
    my $dbh = $c->model('DBI')->dbh;
    
  my $tree = new DBIx::Tree(connection => $dbh,
                            sql      => $sql,
                            method     => \&__disp_tree,
                            columns    => ['id_se', 'name_se', 'parent_se_id'],
                            start_id   => 1,
                            recursive  => 1
                           );                          
   $tree->traverse;    
   

}



sub __disp_tree {
    my %parms = @_;
    my $id    = $parms{id};
     return $id;
}



      

1;


но выдает ошибку странную:
Код

Couldn't instantiate component "MyApp::Model::Tree", COMPONENT() method (from MyApp::Model::Tree) 
didn't return an object-like value (value was 1). at ./myapp_server.pl line 55



в гугле ничего не нашел, но нашел тут и тут

извенив код:

Код

package MyApp::Model::Tree;

 use strict;
use warnings;

use parent 'Catalyst::Component';

use Class::C3::Adopt::NEXT;
use DBIx::Tree;

  sub COMPONENT {
      my $class = shift;
      # Note: $app is like $c, but since the application isn't fully
      # initialized, we don't want to call it $c yet.  $config 
      # is a hashref of config options possibly set on this component.
      my ($app, $config) = @_;

      # Do things here before instantiation
      my $new = $class->next::method(@_);
      # Do things to object after instantiation
      return $new;
  }

sub new {
    my ( $self, $c ) = @_;
    
    $self = $self->next::method(@_);
    

    
        my $sql = "SELECT id_se, name_se, parent_se_id
                       FROM section ";    
        
    my $dbh = $c->model('DBI')->dbh;
    
  my $tree = new DBIx::Tree(connection => $dbh,
                            sql      => $sql,
                            method     => \&__disp_tree,
                            columns    => ['id_se', 'name_se', 'parent_se_id'],
                            start_id   => 1,
                            recursive  => 1
                           );                          
   $tree->traverse;    
  
}




sub __disp_tree {

    my %parms = @_;
    my $id    = $parms{id};
     return $id;

}
      

1;


мне пишет:
Код

Use of uninitialized value in print at /home/x0/data4/MyApp/script/../lib/MyApp/Model/Tree.pm line 46.
Can't call method "find_method_by_name" on an undefined value at /usr/local/lib/perl5/site_perl/5.8.9/Catalyst.pm line 2213.
Compilation failed in require at ./myapp_server.pl line 55.



в гугле я не нашел ничего, как это исправить?

давно что-то гемороя не было такого smile


===

и почему например в описании

Код

  sub COMPONENT {
      my ($class, $app, $args) = @_;
      $args = $self->merge_config_hashes($self->config, $args);
      return $class->new($app, $args);
  }


$self не определено? 




Это сообщение отредактировал(а) gcc - 6.10.2009, 05:37
PM WWW ICQ Skype GTalk Jabber   Вверх
gcc
Дата 6.10.2009, 08:09 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Агент алкомафии
****


Профиль
Группа: Участник
Сообщений: 2691
Регистрация: 25.4.2008
Где: %&й

Репутация: 2
Всего: 17



какая-то странная и тупиковая ситуация

вообщем вот подправил еще:

Код

package MyApp::Model::Tree;

 use strict;
use warnings;

use parent 'Catalyst::Component';

  use MRO::Compat;
use DBIx::Tree;

  sub COMPONENT {
  my $self = shift;
      my ($class, $app, $args) = @_;
      $args = $self->merge_config_hashes($self->config, $args);
      return $class->new($app, $args);
  }

sub new {
    my ( $self, $c ) = @_;
    
    $self = $self->next::method(@_);

        my $sql = "SELECT id_se, name_se, parent_se_id
                       FROM section ";    
        
    my $dbh = $c->model('DBI')->dbh;
    
        print '1111';
    
              my  $sth = $dbh->prepare($sql);
            $sth->execute();
            
             my $id = $sth->fetchrow_arrayref();
            
            $sth->finish();
            
            return $id;
}

1;



вызываю:
Код

  my $tt = $c->model('Tree')->new;
 
 use Data::Dumper;
  print Dumper( $tt ); 


выводит
Код

$VAR1 = bless( {
                 'stash' => {},
                 'stack' => [],
                 'counter' => {},
                 'state' => 0
               }, 'MyApp' );
HTTP/1.0 200 OK



в документации ничего не написано, в слепую наверное надо это решать



вот есть из книги 2 годичной давности, ничего, тоже не получается

Цитата

Tweaking the Model

With the core functionality in place, we can now dig a bit deeper into the model and add some more features. The first one is a sort of "user interface" improvement. Instead of making the user type out the Model::Filesystem part in the config file, it would be nice to just specify "base" and have that take the effect in the same way. We can achieve this by reading the value of $c->config->{base} into $c->config->{Model::Filesystem}->{base} just before Catalyst creates an instance of the class. This is done by overriding the COMPONENT method in the model. The COMPONENT method is called to setup things like configuration right before the new method is called (things like database connections are set up). We can override this in our model, tweak the config, and then call the version of COMPONENT in Catalyst::Model to finish everything up:

    sub COMPONENT {
        my ($class, $app, $args) = @_;
        $args->{base} = $app->config->{base};
        return $class->NEXT::COMPONENT($app, $args);
    }

We call $c $app at this point, because $c usually means that there is a request occurring, whereas $app is just the static data that "is" your application. The current version of Catalyst lets you treat these objects the same way, but Catalyst 5.8 will distinguish between them. This will allow Catalyst applications to embed each other, among other things.

With this code in place, we can change the config file to:

    ---
    base: /tmp/test
    name: Blog

The last feature we'll add is validation of "base" in the new method. This will check to see if the base directory exists, and if it does not, issue an error message and prevent the application from starting:

    sub new {
        my $class = shift;
        my $self = $class->NEXT::new(@_); # get the real self
        my $base = $self->base;
        croak "base $base does not exist" if !-d $base;
        return $self;
    }

If you're inheriting from a base class, you can control whether or not your code runs before that of your base class by choosing whether to run your code before or after the NEXT::new() call. NEXT::new() is where the superclasses get a chance to set themselves up, then control is passed back to you. You should return the result of NEXT::new() from the new method.


http://www.packtpub.com/article/catalyst-w...-your-own-model

Это сообщение отредактировал(а) gcc - 6.10.2009, 08:10
PM WWW ICQ Skype GTalk Jabber   Вверх
gcc
Дата 6.10.2009, 10:06 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Агент алкомафии
****


Профиль
Группа: Участник
Сообщений: 2691
Регистрация: 25.4.2008
Где: %&й

Репутация: 2
Всего: 17



ради интереса, упростил еще проще


Код

package MyApp::Model::Tree;

 use strict;
use warnings;

    use base 'Catalyst::Model';

  use MRO::Compat;
use DBIx::Tree;

sub new {
    my ( $self, $c ) = @_;
  
#    
    $self = $self->next::method(@_);
    
}    
    
sub extr_new {
    my ( $self, $c ) = @_;
  
#    
#    $self = $self->next::method(@_);


        my $sql = "SELECT id_se, name_se, parent_se_id
                       FROM section ";    
        
    my $dbh = $c->model('DBI')->dbh;
    
        print '1111';
    
              my  $sth = $dbh->prepare($sql);
            $sth->execute();
            
             my $id = $sth->fetchrow_arrayref();
            
            $sth->finish();
            
            return $id;


}
   

1;


ругается
Код

Caught exception in MyApp::Controller::delete->delete_section "Can't call method "model" 
on an undefined value at /home/x0/data4/MyApp/script/../lib/MyApp/Model/Tree.pm line 29."


вот на эту строку:
Код

    my $dbh = $c->model('DBI')->dbh;


PM WWW ICQ Skype GTalk Jabber   Вверх
  
Ответ в темуСоздание новой темы Создание опроса
Правила форума "Perl: CGI программирование"
korob2001
sharq
  • В этом разделе обсуждаются вопросы относящиеся только к CGI программированию
  • Если ваш вопрос не относится к системному или CGI программированию, задавайте его в общем разделе
  • Если ваш вопрос относится к системному программированию, задавайте его здесь
  • Интерпретатор Perl можно скачать здесь ActiveState, O'REILLY, The source for Perl
  • Справочное руководство "Установка perl-модулей", качать здесь


Если Вам понравилась атмосфера форума, заходите к нам чаще! С уважением, korob2001, sharq.

 
0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | Perl: разработка для Web | Следующая тема »


 




[ Время генерации скрипта: 0.1932 ]   [ Использовано запросов: 22 ]   [ GZIP включён ]


Реклама на сайте     Информационное спонсорство

 
По вопросам размещения рекламы пишите на vladimir(sobaka)vingrad.ru
Отказ от ответственности     Powered by Invision Power Board(R) 1.3 © 2003  IPS, Inc.