Jump to main content Jump to doc navigation

modX::getService

Note: getService pushed to xPDO layer

Load and return a named service class instance. Returns either a reference to the service class instance or null if it could not be loaded. You can think of this is a simple dependency injector.

Note that the class is instantiated only once: subsequent calls return a reference to the stored instance.

Syntax

API Doc: modX::getService()

object getService (string $name, [string $class = ''], [string $path = ''], [array $params = array ()])
  • $name (string) a key which uniquely identifies the service.
  • $class (string) the full name of the class compatible with the "new" operator OR you can use "dot notation" to specify sub-folders relative to $path
  • $path (string) full path to the directory containing the class in question.
  • $params (array) passed as the 2nd argument to the constructor. The first argument is always a reference to xPDO/MODX.

Examples

Get the modSmarty service.

$modx->getService('smarty','smarty.modSmarty');

Get a custom, user-defined service called 'modTwitter' from a custom path ('/path/to/modtwitter.class.php'), and pass in some custom parameters.

$modx->getService('twitter','modTwitter','/path/to/',array(
  'api_key' => 3212423,
));
$modx->twitter->tweet('Success!');

Another example of using getService inside a custom Extra:

// Use path to point directly to the relevant sub-dir:
if(!$Product = $this->modx->getService('mypkg.product','Product',MODX_CORE_PATH.'components/mypkg/model/mypkg/')) {
    return 'NOT FOUND';
}
// Or use dot-notation in the classname and point the $path to the model directory:
if(!$Product = $this->modx->getService('mypkg.product','mypkg.Product',MODX_CORE_PATH.'components/mypkg/model/')) {
    return 'NOT FOUND';
}

getService may have trouble with PHP namespaces.

See Also

Support the team building MODX with a monthly donation.

The budget raised through OpenCollective is transparent, including payouts, and any contributor can apply to be paid for their work on MODX.

Backers

  • modmore
  • STERC
  • Jens Wittmann – Gestaltung & Entwicklung
  • Fabian Christen
  • Digital Penguin
  • Dannevang Digital
  • Sepia River Studios
  • CrewMark
  • Chris Fickling
  • deJaya
  • Following Sea
  • Anton Tarasov
  • eydolan
  • Raffy
  • Lefthandmedia
  • Murray Wood
  • Snow Creative
  • Nick Clark
  • Helen
  • JT Skaggs
  • krisznet
  • YJ
  • Yanni
  • Richard

Budget

$366 per month—let's make that $500!

Learn more