XF 2.0 Creating a function in another file

AndyB

Well-known member
In my Similar threads add-on, I have a code that is repeated in three different files. I would like to take this code and put it into a file that I can call.

I assume I need to create a folder called "Repositiory" and a file called "SimilarThreads.php", is this correct?

1510003478733.webp

What should SimilarThreads.php file contain? What do I have to add to the three files that will be calling this function? I will need to pass the threadId and nodeId and retreive the threadIds.

Thank you.
 
The repo file.
Code:
<?php

namespace My\AddOn\Repository;

use XF\Mvc\Entity\Repository;

class SimiliarThreads extends Repository
{
   public function myFunction($var)
   {
     if ($var== 'xyz') { return true; }
      return false;
   }
}

And then you can call the function from the repo like this.
Code:
public function actionIndex()
{
   $var = 'xyz';
   $bool = $this->getSimiliarThreadsRepo()->myFunction($var);

   $viewParams = [
      'bool' => $bool
   ];
   return $this->view('My\AddOn:View', 'my_addon_template', $viewParams);
}

/**
* @return \My\AddOn\Repository\SimiliarThreads
*/
protected function getSimiliarThreadsRepo()
{
   return $this->repository('My\AddOn:SimiliarThreads');
}
 
Last edited:
Hi Rayman,

Thank you very much for the detailed explanation.

This is my Andy/SimilarThreads/XF/Pub/Controller/Thread.php file:

PHP:
<?php

namespace Andy\SimilarThreads\XF\Pub\Controller;

use XF\Mvc\ParameterBag;

class Thread extends XFCP_Thread
{
    protected function getSimilarThreadsRepo()
    {
       return $this->repository('Andy\SimilarThreads:SimilarThreads');
    }
  
    public function actionIndex(ParameterBag $params)
    {
        $var = 'xyz';
        $bool = $this->getSimilarThreadsRepo()->myFunction($var);

        if ($bool)
        {
            echo 'Hello world';
        }
...


and my Andy/SimilarThreads/Repository/SimilarThreads.php file:

PHP:
<?php

namespace Andy\Repository;

use XF\Mvc\Entity\Repository;

class SimilarThreads extends Repository
{
    public function myFunction($var)
    {
        if ($var == 'xyz')
        {
            return true;
        }
      
        return false;
    }
}


but I get the following error message when trying to view a thread:

HTML:
LogicException: Could not find repository 'Andy\SimilarThreads\Repository\SimilarThreads' for 'Andy\SimilarThreads:SimilarThreads' in src/XF/Mvc/Entity/Manager.php at line 245


What am I doing incorrectly?

Thank you.
 
Back
Top Bottom