A
A
AlexRas2018-09-18 10:01:52
Yii
AlexRas, 2018-09-18 10:01:52

How to get the name of a component in Yii2?

In configuration like this:

<?php

return [
  'components' => [
    'testComponent' => [
      'class' => 'common\components\TestComponent',
    ],
  ],
];

How can I get the component name "testComponent"? Inside the component class:
<?php

namespace common\components;

class TestComponent extends Component
{
    public function create()
    {
         $config = ArrayHelper::getValue(Yii::$app->components, '{Как тут вывести имя "testComponent"}', []);
         return Yii::createObject($config);
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2018-09-18
@AlexRas

If I understand you correctly, then in the configuration file, set the name of the component.

'components' => [
   'testComponent' => [
        'class' => 'app\components\TestComponent',
       'name' => 'testComponent'
   ]
]

In the component class itself, create a public property and access it like this
class TestComponent extends Component
{
      public $name;

    public function create()
    {
         $config = ArrayHelper::getValue(Yii::$app->components, Yii::$app->testComponent->name, []);
         return Yii::createObject($config);
    }

}

You can get the full path to the component class viaYii::$app->testComponent->className()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question