How to Create Custom Component in Yii Framework
Yii framework having default application components and it is giving different type services.
#Example: ‘urlManager’ component, ‘db’ component etc.
Every application component has an uniqueID and will call through expression format.
We can create Application components like global or local variables.
You may also like - Yii Interview Questions Answers
Yii framework: Types of Components in Yii2:
- Core Components
- Custom Components
1. Core Components
Yii::$app->componentID;
Core Application Components Examples
Yii::$app->db; //DB Component
Yii::$app->cache; //Cache Component
Yii::$app->request;
Yii::$app->session;
Yii::$app->mailer;
2. Custom Components
- Create a folder named "components" in the project common folder.
- Now create one class FullStackTutorialsComponent with extends class ‘Component’ inside the components folder.Using this component, we will display message.
- Please see the below code to create a custom component class.
- Config Component In Yii2 We have to register 'FullStackTutorialsComponent' inside the common/config/main.php or common/config/main-local.php file.
- Call Yii2 Custom Component Function in Yii Framework Now we can access this component using ‘Yii::$app->fullstacktutorials’ expression
namespace common\components;
use Yii;
use yii\base\Component;
use yii\helpers\Html;
class FullStackTutorialsComponent extends Component{
public $content;
public function init(){
parent::init();
$this->content= 'Hello This is Default Message of Custom Component in Yii2';
}
public function display($content=null){
if($content!=null){
$this->content= $content;
}
echo Html::encode($this->content);
}
}
'components' => [
'fullstacktutorials' => [
'class' => 'common\components\FullStackTutorialsComponent',
],
],
echo Yii::$app->fullstacktutorials->display('Congrats! This is your custom Component.');
You may also like - PHP Interview Questions Answers