Перейти к содержанию

UnexpectedValueException для простого плагина


Рекомендуемые сообщения

Привет ребят,

Я получаю следующую ошибку для очень простого плагина. Поскольку я не силен в программировании, я пытаюсь сделать свой собственный плагин, сравнивая его с другими. Поэтому я не уверен, что я делаю неправильно, но я потратил много часов, пытаясь это исправить. Неудачно.

Spoiler

UnexpectedValueException:  (0)
#0 domain.com/applications/forums/modules/front/forums/index.php(216): IPS\_Theme->getTemplate('index')
#1 domain.com/system/Dispatcher/Controller.php(101): IPS\forums\modules\front\forums\_index->manage()
#2 domain.com/applications/forums/modules/front/forums/index.php(52): IPS\Dispatcher\_Controller->execute()
#3 domain.com/system/Dispatcher/Dispatcher.php(153): IPS\forums\modules\front\forums\_index->execute()
#4 domain.com/index.php(13): IPS\_Dispatcher->run()
#5 {main}

 

1st hook (theme): \IPS\Theme\class_forums_front_index
CSS selector: li.cForumRow.ipsDataItem.ipsDataItem_responsivePhoto.ipsClearfix > div.ipsDataItem_main > ul.ipsDataItem_subList.ipsList_inline

Spoiler

{{if $forum->forumstyle() )}}
    <ul class="ipsDataItem_subList ipsList_inline">
    {{else}}
    <ul class="ipsDataItem_subList ipsList_csv">
{{endif}}

 

2nd hook (code): \IPS\forums\modules\front\forums\forums

Spoiler

//<?php

/* To prevent PHP errors (extending class does not exist) revealing path */
if ( !\defined( '\IPS\SUITE_UNIQUE_KEY' ) )
{
    exit;
}

class hook94 extends _HOOK_CLASS_
{
    public static function forumstyles( \IPS\forums\Forum $forum )      
        {    
            try
            {
                    if ( \IPS\Settings::i()->fs_style1 == 'style1' AND in_array( $forum, explode(',', \IPS\Settings::i()->fs_forums)) )
                    {
                        return TRUE;
                    }

                    return FALSE;

            }
                catch ( \RuntimeException $e )
                {
                      if ( method_exists( get_parent_class(), __FUNCTION__ ) )
                      {
                          return \call_user_func_array( 'parent::' . __FUNCTION__, \func_get_args() );
                      }
                      else
                      {
                          throw $e;
                      }
                }
        } 
}

 

Я также пытался расширить \IPS\forums\modules\front\forums\index, но это тоже не работает. Я даже пытался изменить функции кода, та же ошибка.

Может ли кто-нибудь указать мне правильное направление?

Forum Lists Style 1.0.2 (6).xml

Ссылка на комментарий
Поделиться на другие сайты

Firstly.. when u "replace" something in theme hook, you don't replace the line you selected, but everything that includes this tag.

if html like 

<div class='black'>
<ul>...
<li>....
</div>

and you select first string, your hook replace all div, not first (<div class='black'>) string

 

Ссылка на комментарий
Поделиться на другие сайты

8 hours ago, Desti said:

Firstly.. when u "replace" something in theme hook, you don't replace the line you selected, but everything that includes this tag.

if html like 

<div class='black'>
<ul>...
<li>....
</div>

and you select first string, your hook replace all div, not first (<div class='black'>) string

 

You're right. I was making the plugin so late at night that I didn't realize such silly mistakes. There were others too, like having an extra '(' somewhere or not using the proper setting name.

It's a bit better, but I'm getting this message now:

Spoiler

[[Template forums/front/index/forumRow is throwing an error. This theme may be out of date. Run the support tool in the AdminCP to restore the default theme.]]

 

1st hook (theme): \IPS\Theme\class_forums_front_index

Spoiler

              {{if $forum->forumstyle()}}
                <ul class="ipsDataItem_subList ipsList_csv">
              {{else}}
                <ul class="ipsDataItem_subList ipsList_inline">
              {{endif}}
                    {{foreach $forum->children() as $subforum}}
                        <li class="{{if \IPS\forums\Topic::containerUnread( $subforum )}}ipsDataItem_unread{{endif}}">
                            <a href="{$subforum->url()}">{{if \IPS\forums\Topic::containerUnread( $subforum )}}<span class='ipsItemStatus ipsItemStatus_tiny {{if !\IPS\forums\Topic::containerUnread( $subforum ) && !$subforum->redirect_on}}ipsItemStatus_read{{endif}}'><i class="fa fa-circle"></i></span> {{endif}}{$subforum->_title}</a>
                        </li>
                    {{endforeach}}
                </ul>

 

2nd hook (code): \IPS\forums\modules\front\forums\forums

Spoiler

//<?php

/* To prevent PHP errors (extending class does not exist) revealing path */
if ( !\defined( '\IPS\SUITE_UNIQUE_KEY' ) )
{
    exit;
}

class hook109 extends _HOOK_CLASS_
{
    public function forumstyles( $forum )      
        {    
            try
            {
                    if ( \IPS\Settings::i()->forumstyle == 'style1' AND in_array( $forum, explode(',', \IPS\Settings::i()->fs_forums)) )
                    {
                        return TRUE;
                    }

                    return FALSE;

            }
                catch ( \RuntimeException $e )
                {
                      if ( method_exists( get_parent_class(), __FUNCTION__ ) )
                      {
                          return \call_user_func_array( 'parent::' . __FUNCTION__, \func_get_args() );
                      }
                      else
                      {
                          throw $e;
                      }
                }
        } 
}

 

Settings:

 

Spoiler

image.thumb.png.826534b3197e83f7e3449e84de803184.png

 

{{if $forum->forumstyle()}} is actually {{if $forum->forumstyles()}}, but I'm still getting an error.

Forum Lists Style 1.0.3 (1).xml

Ссылка на комментарий
Поделиться на другие сайты

I've also tried different types of functions and arguments, like:

Spoiler

public function forumstyles( $forum )
public function forumstyles( \IPS\forums\Forum $forum )
public static function forumstyles( \IPS\forums\Forum $forum )
etc.

 

Ссылка на комментарий
Поделиться на другие сайты

You call instance of \IPS\forums\Forum ($forum), but add function to \IPS\forums\modules\front\forums\index, why? 

 

Ссылка на комментарий
Поделиться на другие сайты

4 minutes ago, Desti said:

You call instance of \IPS\forums\Forum ($forum), but add function to \IPS\forums\modules\front\forums\index, why? 

I'm not sure I learned the logic of classes and functions yet, so I just checked other plugins and tried to do something similar. What do you suggest I do instead, or how should I think like so the functions make sense?

Edit:

From my newbie perspective, I think adding it to '\IPS\forums\modules\front\forums\index' makes sense because that's where forumRow is located in. I also think it makes sense adding it to \IPS\forums\modules\front\forums\forums, because that's where I see the argument $forum being created.

Ссылка на комментарий
Поделиться на другие сайты

$forum in template is instance of \IPS\forums\Forum. U can see it if var_dump $forum variable

image.png.70f1f296001cb767d10b9a5e790e2975.png

image.png.59ccda0a7384b24b269a2073db4e40bb.png

And your hook must be from \IPS\forums\Forum

Ссылка на комментарий
Поделиться на другие сайты

21 minutes ago, Desti said:

$forum in template is instance of \IPS\forums\Forum. U can see it if var_dump $forum variable

And your hook must be from \IPS\forums\Forum

Great tip!! I didn't know about var_dump, it'll make it much easier from now on. I was able to reproduce it here:

Spoiler

image.png.96626f4329219ca51a674bcd861ed315.png

 

So, now that we have figured the hook has to be from \IPS\forums\Forum, what would be the proper function? static function? Just function? Do I add \IPS\forums\Forum before $forum?  This is the most confusing part for me. I'm trying this but it's still throwing an error:

Spoiler

//<?php

/* To prevent PHP errors (extending class does not exist) revealing path */
if ( !\defined( '\IPS\SUITE_UNIQUE_KEY' ) )
{
    exit;
}

class hook113 extends _HOOK_CLASS_
{
    public static function forumstyles( $forum )      
        {    
            try
            {
                    if ( \IPS\Settings::i()->forumstyle == 'style2' AND in_array( $forum, explode(',', \IPS\Settings::i()->fs_forums)) )
                    {
                        return TRUE;
                    }

                    return FALSE;

            }
                catch ( \RuntimeException $e )
                {
                      if ( method_exists( get_parent_class(), __FUNCTION__ ) )
                      {
                          return \call_user_func_array( 'parent::' . __FUNCTION__, \func_get_args() );
                      }
                      else
                      {
                          throw $e;
                      }
                }
        } 
}

 

Forum Lists Style 1.0.4 (1).xml

Изменено пользователем BlackShot
Ссылка на комментарий
Поделиться на другие сайты

1. Publiс function. No "public static" -> public function forumstyles( $forum ) { ... }
2. no type declaration on function variable
3. in template you must add param to function ->  {{if $forum->forumstyle( $forum->name )}} - for example. 

 if ( \IPS\Settings::i()->forumstyle == 'style2' AND in_array( $forum, explode(',', \IPS\Settings::i()->fs_forums)) ) - this you can insert directly into the template, no hook needed
{{if \IPS\Settings::i()->forumstyle == 'style2' AND in_array( $forum->id(or what?), explode(',', \IPS\Settings::i()->fs_forums)) }} - i don't know what is stored in\IPS\Settings::i()->fs_forums...

\IPS\Settings::i()->fs_forums - array of ID, you must use $forum->id

Ссылка на комментарий
Поделиться на другие сайты

1 hour ago, Desti said:

1. Publiс function. No "public static" -> public function forumstyles( $forum ) { ... }
2. no type declaration on function variable
3. in template you must add param to function ->  {{if $forum->forumstyle( $forum->name )}} - for example. 

 if ( \IPS\Settings::i()->forumstyle == 'style2' AND in_array( $forum, explode(',', \IPS\Settings::i()->fs_forums)) ) - this you can insert directly into the template, no hook needed
{{if \IPS\Settings::i()->forumstyle == 'style2' AND in_array( $forum->id(or what?), explode(',', \IPS\Settings::i()->fs_forums)) }} - i don't know what is stored in\IPS\Settings::i()->fs_forums...

\IPS\Settings::i()->fs_forums - array of ID, you must use $forum->id

Wow, I can't believe a function wasn't necessary at all. What would be the purpose of having a function then? To make it easier and simpler if you have a lot of theme hooks, for example?

Everything works fine now, thanks to you Desti! I even removed the 'forumstyle' setting. Just a list of forums is enough for now.

BTW, where can I check if an argument like $forum is enough or if I need to write $forum->id?

Ссылка на комментарий
Поделиться на другие сайты

1 час назад, BlackShot сказал:

$forum is enough or if I need to write $forum->id?

$forum - big object with data, $forum->id - small part of this object, forum ID. If you need in your function all forum data, you must set $forum as arg, but if you need only ID, set $forum->id as arg. 

function test($forum) { // arg as object ( called as test($forum) )
   return $forum->id. '---> ' . $forum->name; // you use data from object
}

and 

function test($forum) { // arg as ID only ( called as test($forum->id) )
   return 'Forum ID: $forum; // you use id only

}

1 час назад, BlackShot сказал:

What would be the purpose of having a function then?

Depends on the complexity of the task that the function solves. Simple true-false checks can be placed in the template, complex calculations and database queries can be placed in the hook function.

Ссылка на комментарий
Поделиться на другие сайты

3 hours ago, Desti said:

$forum - big object with data, $forum->id - small part of this object, forum ID. If you need in your function all forum data, you must set $forum as arg, but if you need only ID, set $forum->id as arg. 

function test($forum) { // arg as object ( called as test($forum) )
   return $forum->id. '---> ' . $forum->name; // you use data from object
}

and 

function test($forum) { // arg as ID only ( called as test($forum->id) )
   return 'Forum ID: $forum; // you use id only

}

Depends on the complexity of the task that the function solves. Simple true-false checks can be placed in the template, complex calculations and database queries can be placed in the hook function.

And in this case, such data (id, name) can be found in forums\sources\Forum\Forum.php, right? Which is where the class \IPS\forums\Forum is located in.

This is becoming fun - I feel like I've been learning a lot from you and these forums. Do you recommend any guides, videos or content for beginners at coding, Desti? Or do you have any tips? I'm finding all of this super interesting. I hope to contribute a lot more in the future with plugins and (who knows?) apps.

Изменено пользователем BlackShot
Ссылка на комментарий
Поделиться на другие сайты

IPS (conditionally) has 3 types of classes: system/- IPS engine classes, sources/- application data structure/storage classes and modules/- application data view classes. 

5 часов назад, BlackShot сказал:

such data (id, name) can be found in forums\sources\Forum\Forum.php, right?

Partly.. Forum.php inherits system classes \IPS\Node\Model /  \IPS\Patterns\ActiveRecord - base structures to store such data and describes some specific storage conditions. 

Search "object oriented PHP" on youtube - good start point

Ссылка на комментарий
Поделиться на другие сайты

Присоединяйтесь к обсуждению

Вы можете написать сейчас и зарегистрироваться позже. Если у вас есть аккаунт, авторизуйтесь, чтобы опубликовать от имени своего аккаунта.
Примечание: Ваш пост будет проверен модератором, прежде чем станет видимым.

Гость
Ответить в этой теме...

×   Вставлено с форматированием.   Вставить как обычный текст

  Разрешено использовать не более 75 эмодзи.

×   Ваша ссылка была автоматически встроена.   Отображать как обычную ссылку

×   Ваш предыдущий контент был восстановлен.   Очистить редактор

×   Вы не можете вставлять изображения напрямую. Загружайте или вставляйте изображения по ссылке.

  • Последние посетители   0 пользователей онлайн

    • Ни одного зарегистрированного пользователя не просматривает данную страницу
×
×
  • Создать...