Yii2: Access your services within your module

Submitted by Peter Majmesku on Mon, 08/29/2016 - 19:22

There're some ways to declare the service in your config file for global use, but I wanted a way to setup my service in my module. Well, it took me a while so I write the way down here to look back in future to not search around the web.

Firstly you need to declare the service in your module:

namespace app\modules\MY-MODULE;
Module extends \yii\base\Module
$controllerNamespace 'app\modules\MY-MODULE\controllers';
    public function 
// Declare services. Let's say you need the XmlService.
$this->set('xml', new services\XmlService());

Afterwards you can access your module wherever you want to (note the cast for handier usage in your IDE):

/* @var $xml app\modules\yiipass\services\xml */
$xml = \Yii::$app->getModule('MY-MODULE')->get('xml');