MODX3 new services question

I’m trying to understand the new services part of MODX3. My question is - if I’d like to add goodnews as a member of the modx class so it can be accessed like this:


Should the following two snippets work equally?

$modx->services->add('goodnews', function ($c) use ($modx) {
    return new \Bitego\GoodNews\GoodNews($modx);
$modx->services->add('goodnews', new  \Bitego\GoodNews\GoodNews($modx));
$modx->goodnews = $modx->services->get('goodnews');

I’d suggest not wanting to have $modx->goodnews - dynamic properties like that are going away in PHP eventually.

Just add the service, perhaps using the classname:

use \Bitego\GoodNews\GoodNews;

$modx->services->add(GoodNews::class, function ($c) use ($modx) {
    return new GoodNews($modx);

and retrieve it where needed like so:

use \Bitego\GoodNews\GoodNews;
$goodnews = $modx->services->get(GoodNews::class);

Ok, thanks! didn’t know that.

What is the benefit of using a closure function in this case (like in the docs)?

The following two code parts should do the same, or not?

$modx->services->add('goodnews', function ($c) use ($modx) {
    return new GoodNews($modx);

$modx->services->add('goodnews', new GoodNews($modx));

I haven’t seen that second syntax used with the pimple container we currently use. Where’d you get it from?

Not sure if it’s valid, but if it is, one key difference would be that the first (official) syntax would only run the closure when the service is requested the first time. Your other syntax would run immediately.

Great hint! Thanks Mark!

For the “unofficial” service->add() way, you always need to check if service already exists before adding.

Yikes, I don’t think that blog necessarily offers great advice :grimacing: I’d definitely use the expected syntax of providing the container with a callable to avoid side effects or unexpected behavior if we switch to a different container implementation later (i.e. php-di).

1 Like

This topic was automatically closed 2 days after discussion ended and a solution was marked. New replies are no longer allowed. You can open a new topic by clicking the link icon below the original post or solution and selecting “+ New Topic”.