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;
class 
Module extends \yii\base\Module
{
    public 
$controllerNamespace 'app\modules\MY-MODULE\controllers';
    public function 
init()
    {
        
parent::init();
        
// 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'); 
Tags

Add new comment

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.
CAPTCHA This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.