Passing the modx reference to an autoloaded class


Really missing something here - I am trying to use modx methods in classes that are autoloaded (via composer) and not quite understanding how to pass the reference … in my example the logtest method in myClass works fine and adds an entry to the modx log.
the method anotherLogTest does autoload the external class ‘yourClass’ but gives too few argument errors to myClass::__construct.

How do I correctly do this?

if (!class_exists('myClass')) {

	require_once dirname(dirname(__FILE__)).'/vendor/autoload.php';

	class myClass {

		public $config = array();

		function __construct(modX & $modx,array $config = array()) {
			$this->output = '';
			$this->modx =& $modx;
			setlocale(LC_MONETARY, 'en_CA');

		} // construct

	     * test 1
	    public function logTest(){

			$logentry = 'This is a log entry';

			$this->modx->log(modX::LOG_LEVEL_ERROR, 'log entry  = ' . $logentry);



	     * test 2
	    public function anotherLogTest(){

			$logentry = 'This is a log entry';

			$do = new yourClass();




	} // myClass

} //if

// external autoloaded file
class yourClass extends myClass {

	// how do I get the modx reference?? 

    public function logging($logentry){

			$this->modx->log(modX::LOG_LEVEL_ERROR, 'log entry  = ' . $logentry);

	        return ;



You’re not passing any parameters to the constructor there, so that’s going to cause a fatal error.

Simplest would be to do this:

$do = new yourClass($this->modx);

and make sure to add public $modx or protected $modx in myClass to avoid warnings. May want to add a null default (public $modx = null) and/or use typed properties (public modX $modx;).

Thanks . yes - it was a quick example, the real one is far too verbose…

So, I think I understand a little better - I wasn’t really clear in on how our extras got the reference in the first place (when called from a snippet using getService) i.e.

$myClass= $modx->getService('myclass', 'myClass', $core, $scriptProperties);

I guess that is passed along in the getservice method?

Anyway … so I see what you are suggesting there. There are going to be a LOT of external classes and a lot of calls to them. Other than what you have outlined would there be a clever way to pass the reference in the autoloader (as nearly every class will use something ~ modx )


Yes, the getService function creates a new object of type “myClass” and passes itself ($this) as a parameter.

1 Like

Could look into using a container like PHP-DI with autowiring for your use case. Or clever abstractions. getService is mostly meant for services (utilities) that are shared across different parts of the application.

MODX 3 has a container built in but does not currently expose itself in it so a modX parameter won’t get autowired just yet. It also currently uses Pimple which does not do autowiring, so this is moot.