Using functions in a package

I wonder if anyone can help. I wanted to use a function I created in a package. So I placed it into the controller and I can use it in my theme.

However I also wanted to use in in a block template I have in the package. But for some reason it doesn’t want to see it, I presume blocks use there own controllers.

So my question is where can I put the code to use it in both.

Ideas on a postcode… (when I say postcard I mean in here please, lol)

Looks like this might do it.

Be careful, the way class namespaces are unscrambled had some quirks in 5.7 that were partly maintained for back compatibility in v8, so forum threads of that age could be at the confusing join between the two.

As a general strategy, you can declare an autoload mapping array in your package controller such as:

protected $pkgAutoloaderRegistries = [
        'src/JtF/SearchPlusPlus'         => '\\JtF\\SearchPlusPlus\\'
    ];

Escaping the backslashes is not strictly necessary, just something I am in the habit of doing.

This tells the autoloading system to find classes in the namespace
\JtF\SearchPlusPlus

in the direrctory
src/JtF/SearchPlusPlus

So, for example, the file:
packages/jl_search_plus_plus/src/JtF/SearchPlusPlus/StopWords.php

Contains the class

namespace JtF\SearchPlusPlus;
class StopWords
{ ...

And that will be autoloaded when another class or file states:
use JtF\SearchPlusPlus\StopWords;

That system works nicely for general purpose classes shared within a package and automatically descends into subdirectories and sub-namespaces. Within a namespace, class names and directory names must match case exactly.

There are some historical quirks about mapping class names for blocks and any kind of controller, but I guess you are already familiar with that from developing blocks.

You can find plenty of examples from recent free packages in the marketplace from regular developers.