Tagger PHP scripting for MODX 3.0 / 2.8.x compatibility

I’m trying to find an easy way to make scripts using Tagger written for 2.8 compatible with 3.0.

I can put:

use MODX\Revolution\modResource;

at the top of a PHP script and then do a query starting with:

$c = $modx->newQuery('modResource');

But for Tagger, putting

use Tagger\Model\TaggerTag;

at the top does NOT let me do this:

$c = $modx->newQuery('TaggerTag');

I have to put the new setup in the query:

$c = $modx->newQuery('Tagger\Model\TaggerTag');

Is there any way to put a “use” statement at the top of scripts so that I don’t have to manually update all my query statements with when using Tagger? I really don’t want to have to do this for every one:

if($modx->getVersionData()['version'] >= 3) {
  $c = $modx->newQuery('Tagger\Model\TaggerTag');
} else {
  $c = $modx->newQuery('TaggerTag');

Now, I CAN use ‘TaggerTag::class’, which works in both 2.8 and 3.0:

$c = $modx->newQuery(TaggerTag:class);

But, with 3.0, I have to put

use Tagger\Model\TaggerTag;

at the top. If that’s at the top in 2.8, it throws an error and aborts the script. I can’t wrap the “use” line inside a conditional statement to check for the version number, so what to do?

This only works because a class_alias is created here in the code:

This file (core/include/deprecated.php) makes MODX 3 more backwards compatible with older code (but will eventually be removed).

I have seen code like this

$prefix = $modx->getVersionData()['version'] >= 3 ? 'Tagger\\Model\\' : '';
$c = $modx->newQuery($prefix . 'TaggerTag');

where a prefix is defined for MODX 3. But this is kinda ugly as well.

Yeah, I saw that and was hoping to avoid it. Any way to create an alias inside a snippet? If not, the ugly way may be the only way.

I suppose I can create a plugin with this and fire it OnLoadWebDocument:

global $taggerpre;
$taggerpre = $modx->getVersionData()['version'] >= 3 ? 'Tagger\\Model\\' : '';

And in relevant snippets I just put this at the top:

global $taggerpre;

That would keep my code cleaner. I can live with having to globally replace the queries with:

$c = $modx->newQuery($taggerpre . 'TaggerTag');

I wouldn’t consider a global variable as “clean code”!

Is there a (good) reason, why you need the same code to run on both MODX 2 and MODX 3?