Tutorial Yii2 Bagian 35 : Membuat Component
Component dapat digunakan dari mana saja, tidak tergantung pada controller, model, namun sesuatu yang bisa dipanggil dari mana saja. 1. Buat folder components di dalam folder backend, dan di dalam folder components tersebut, buat satu file yang dinamakan MyComponent.php
1 2 3 4 5 6 7 8 9 10 11 12 |
<?php namespace backend\components; use Yii; use yii\base\Component; class MyComponent extends Component{ public function hello(){ echo "This is my Component"; } } |
2. Modifikasi main.php yang berada di dalam folder backend\config untuk menambahkan component.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
<?php $params = array_merge( require(__DIR__ . '/../../common/config/params.php'), require(__DIR__ . '/../../common/config/params-local.php'), require(__DIR__ . '/params.php'), require(__DIR__ . '/params-local.php') ); return [ 'id' => 'app-backend', 'basePath' => dirname(__DIR__), 'controllerNamespace' => 'backend\controllers', 'bootstrap' => ['log'], 'modules' => [ 'settings' => [ 'class' => 'backend\modules\settings\Settings', ], 'gridview' => [ 'class' => '\kartik\grid\Module' // enter optional module parameters below - only if you need to // use your own export download action or custom translation // message source // 'downloadAction' => 'gridview/export/download', // 'i18n' => [] ], ], 'components' => [ 'user' => [ 'identityClass' => 'common\models\User', 'enableAutoLogin' => true, ], 'log' => [ 'traceLevel' => YII_DEBUG ? 3 : 0, 'targets' => [ [ 'class' => 'yii\log\FileTarget', 'levels' => ['error', 'warning'], ], ], ], 'mailer'=>[ 'class'=>'yii\swiftmailer\Mailer', 'useFileTransport'=>false, ], 'authManager'=> [ 'class'=>'yii\rbac\DbManager', 'defaultRoles'=>['guest'], ], 'errorHandler' => [ 'errorAction' => 'site/error', ], 'MyComponent'=>[ 'class'=>'backend\components\MyComponent', ], ], 'params' => $params, ]; |
3. Kita akan coba tampilkan component yang baru Read more about Tutorial Yii2 Bagian 35 : Membuat Component[…]