Creating own component in yii2
Create a folder named "components" inside backend directory. Now create one class 'Converter' with extends class 'Component' inside the components folder. Using this component, we will display unix timestamp to date and time.
Please see the below code to create a custom component class and function for convert unix timestamp to date and time .
PATH : yii-demo/backend/components/Converter.php
<?php namespace app\components; use yii\base\Component; use yii\helpers\Html; class Converter extends Component { public function unixToMySQL($timestamp) { return date('d-m-Y h:i:s A', $timestamp); } } ?>
Configuring our own component in configuration file.
PATH: /opt/lampp/htdocs/advanced/backend/config/main.php
'components' => [ 'helper' => [ 'class' => 'app\components\Converter', ], ],
Let's call our component function inside default site conroller index.
PATH: /opt/lampp/htdocs/advanced/backend/controllers/SiteController.php
public function actionIndex() { // unix timestamp $timestamp = 1485259987; //calling our component function unixtomysql return Yii::$app->helper->unixToMySQL($timestamp); }
No comments: