How To Create And Use Components In Yii2?

Hi all,

I just started playing with Yii2 over the weekend and wanted to create my own component. A found that the component directory no longer exists and that CComponent has now been replaced by (or now extends) \yii\base\object but I can’t find any examples of how I go about this.

I am wanting to create a component that is to connect to a remote API. How would I go about doing this in Yii2? Where to a put this class and how do I use it?

Thanks

Feel free to create it by yourself.

Actually it’s yii\base\Component now.

Also you can see (or even extend) some of the existing components, like Request, authManager and so on.

Create a class extending Object, Component or some of the existing components (depends on what you need), namespace it properly and put into app subfolder (components for example).

Then you can add it to config file and use as usual.

For example,


<?php

// app/components/Request.php

namespace app\components;


class Request extends \yii\web\Request

{

    /**

     * Returns whether this is a PJAX request.

     * @return boolean whether this is a PJAX request.

     */

    public function getIsPjax()

    {

        return isset($_SERVER['HTTP_X_PJAX']);

    }


}






// app/config/web.php

'components' => [

    'request' => [

        'class' => 'app\components\Request',

        'enableCsrfValidation' => true,

    ],

    // ...

]




// somewhere in the app

\Yii::$app->get('yourComponent')->doSomething();



Thanks ORey, that was exactly what I was looking for.

For anyone arriving from Google, Yii2’s new DI/Services architecture makes this obsolete.

The correct syntax is:




Yii::$app->get($serviceID);



Updated.

I wonder if there’s a good way to link forum posts to API for autoupdate :)

And Loading its own library by using PSR-4 ?