D
D
dkrylov2017-07-17 22:43:08
Yii
dkrylov, 2017-07-17 22:43:08

How to implement component in yii2 module?

Hello!
Tell me how to implement the launch and use of the component in the module!
Those. for example, we have a module "shop" in it there is a folder /components/ and there is a component for working with a basket of goods "cart". And through the OrderController, work with this component should be implemented.
In general, am I taking the correct approach? I think those who understand understand what I'm doing and how. Please take a minute of your time)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Screamy Di, 2017-07-18
@dkrylov

Hello.
A module is essentially an application instance and it allows you to use the service locator and DI just like Yii2 itself.
If I understand your question correctly, then you need to include your component in the module configuration via the DI container. Then it will be available from the module.
In configuration it might look something like this:

//...
'modules' => [

        'shop' => [
            'class' => 'common\modules\shop\Module',
            'components' => [

                'cart' => [
                    'class' => 'common\modules\shop\components\Cart',
                    'property' => 'value',
                ],
            ],
        ],
],
//...

In the common\modules\shop\Module class, create public fields components and cart. And in the common\modules\shop\Module::init() method you initialize your Cart component via
$this->cart = Yii::createObject($this->components['cart']), as it is written in the off.docs :
// create an object using a configuration array
$object = Yii::createObject([
    'class' => 'yii\db\Connection',
    'dsn' => 'mysql:host=127.0.0.1;dbname=demo',
    'username' => 'root',
    'password' => '',
    'charset' => 'utf8',
]);

You can do all this without configuration, just by using DI in your module's init() method. But then the code will be tightly coupled and you won't be able to configure your component without editing the module code.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question