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?
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']);
}
}